Symfony2: include raw file in Twig Template - symfony

I would like to include a raw file (user-actions.log) to a Template.
The file is saved in /MyBundle/Ressources/views/Admin/user-actions.log (could change directory if necessary)
Trying to include file with {{ include('MyBundle:Admin:user-actions.log) }} or {% include 'MyBundle:Admin:user-actions.log' }} doesnt work because it isn't a .twig.
How can I solve this?

Write up an twig extension
<?php
namespace Acme\AcmeBundle\Twig;
use Symfony\Component\HttpKernel\KernelInterface;
class Extension extends \Twig_Extension
{
private $kernel;
private $service_container;
public function __construct(KernelInterface $kernel, $service_container)
{
$this->kernel = $kernel;
$this->service_container = $service_container;
}
public function getFunctions()
{
return array(
'includeFile' => new \Twig_Function_Method($this, 'includeFile')
);
}
public function includeFile($file)
{
return file_get_contents($file);
}
}
In services.yml
parameters:
acme.twig.extension.class: Acme\AcmeBundle\Twig\Extension
services:
acme.twig.extension:
class: %acme.twig.extension.class%
arguments:
kernel: "#kernel"
service_container: "#service_container"
tags:
- { name: twig.extension }
In your twig templates you can use
{{ includeFile(your_path_to_the_file.log) }}
More docs
http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Related

Symfony Twig Call Continer

I'm using Symfony 3 with Twig.
In every route I need to make a call to entity:
$posts = $this->getDoctrine()
->getRepository('AppBundle:Posts')
->findAll();
There is a way that I can do this globally?
And call it from the twig instead of in the route?
You can write a service that will do it and inject it as a twig global
#app/config.yml
twig:
globals:
posts_service: '#app_posts_service'
Then define the service
#app/services.yml
services:
app_posts_service:
class: AppBundle\Service\PostsService
arguments: ["#doctrine"]
Make sure your services file is getting imported into your config:
#app/config.yml
imports:
- { resource: services.yml }
Then define the service:
// src/AppBundle/Service/PostsService.php
namespace AppBundle\Service;
class PostsService
{
protected $doctrine;
public function __construct($doctrine)
{
$this->doctrine = $doctrine;
}
public function getAllPosts()
{
return $this->doctrine
->getManager()
->getRepository('AppBundle:Posts')
->findAll();
}
}
Then use it in any twig file like:
{%for post in posts_service.getAllPosts() %}
{{ post.title }} {# or whatever #}
{% endfor %}

Active Bundles of Symfony2

I'm trying to show a menu of my Bundles, but I need show only the Bundles that are active, how can I get the active Bundles in Twig?
Thanks and Regards!
The list of bundle is stored in the kernel.
You have to create a twig extension BundleExtension and pass the kernel as dependency:
<?php
namespace MyBundle\Twig\Extension;
use Symfony\Component\HttpKernel\KernelInterface;
class BundleExtension extends \Twig_Extension
{
protected $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* {#inheritdoc}
* #see Twig_Extension::getFunctions()
*/
public function getFunctions()
{
return array(
'getBundles' => new \Twig_SimpleFunction('getBundles', array($this, 'getBundles')),
);
}
public function getBundles()
{
return $this->kernel->getBundles();
}
/**
* {#inheritdoc}
* #see Twig_ExtensionInterface::getName()
*/
public function getName()
{
return 'get_bundles';
}
}
Register it as a service:
services:
bundle_extension:
class: MyBundle\Twig\Extension\BundleExtension
arguments: ['#kernel']
tags:
- { name: twig.extension }
And now in your twig template:
{% set bundles = getBundles() %}
{% for bundle in bundles %}
{{ bundle.getName()}}<br/>
{% endfor %}

Symfony2 - Twig extension does not exist in Twig file

I am trying to register (read the docs) a Twig extension and everything seems to be correct except it's not being found in the Twig file.
Getting the following error:
The function "getPostCount" does not exist in AcmeDemoBundle:Page:index.html.twig at line 17
Can someone show me what I am doing wrong?
services.yml
acme.twig.acme_extension:
class: Acme\DemoBundle\Twig\PostExtension
tags:
- { name: twig. extension }
arguments:
em: "#doctrine.orm.entity_manager"
PostExtension.php
class PostExtension extends \Twig_Extension
{
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function getFilters()
{
return array(
);
}
public function getFunctions()
{
return array(
'getPostCount' => new \Twig_Function_Method($this,'getPostCount')
);
}
public function getPostCount($year, $month)
{
return $this->$em->getRepository('AcmeDemoBundle:Post')
->getPostCountsByMonth($year, $month);
}
public function getName()
{
return 'post_extension';
}
}
Twig
{{ getPostCount('2014', 'July') }}
In services.yml:
Remove the extra space in twig.extension.
tags:
- { name: twig.extension }

How do I check for the existence of a bundle in twig?

My application is made up with eight bundles, within my main layout I would like to check if a certain bundle exists so I can include a sub template, how do I go about doing this?
Thanks to #DonCallisto, I decided to make a twig function to use in my templates, the following is my twig extension.
<?php
namespace MG\AdminBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Bundles extends \Twig_Extension {
protected $container;
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'bundleExists',
array($this, 'bundleExists')
),
);
}
public function bundleExists($bundle){
return array_key_exists(
$bundle,
$this->container->getParameter('kernel.bundles')
);
}
public function getName() {
return 'mg_admin_bundles';
}
}
I then registered it in my services.yml
services:
mg_admin.bundles.extension:
class: MG\AdminBundle\Twig\Bundles
arguments: [#service_container]
tags:
- { name: twig.extension }
Now in my twig templates I can check for registered bundles like this:
{% if bundleExists('MGEmailBundle') %}
{% include 'MGEmailBundle:SideBar:sidebar.html.twig' %}
{% endif %}
$this->container->getParameter('kernel.bundles');
will return all registered bundles (class names). You could pass that list - or parse it direclty - into a controller and pass it to your twig view
Then you should easily reach your target
If the bundle you want to check is a specific bundle, and you know the main class name, the easiest way may be:
if (class_exists('Acme\CommentBundle\AcmeCommentBundle'))
{
// Bundle exists and is loaded by AppKernel...
}

how to get currency symbol in twig, symfony2?

I am currently able to get currency symbol in symfony2 controller
$formatter = new \NumberFormatter($this->getRequest()->getLocale(),\NumberFormatter::CURRENCY);
$symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
and then pass it to twig.
However, because I need to get this currency symbol in many twig templates, inserting that piece of code in the corresponding controllers is not a pleasant thing to do. So, is there any better/easier way to do this directly in twig?
Thanks.
Here is how I create the custom twig function
namespace Acme\DemoBundle\Twig;
class AcmeExtension extends \Twig_Extension
{
public function getFunctions() {
return array(
'currencySymbol' => new \Twig_Function_Method($this, 'currencySymbolFunction'),
);
}
public function currencySymbolFunction($locale) {
$locale = $locale == null ? \Locale::getDefault() : $locale;
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
return $symbol;
}
public function getName() {
return 'acme_extension';
}
}
The service:
acme.twig.acme_extension:
class: Acme\DemoBundle\Twig\AcmeExtension
tags:
- { name: twig.extension }
Because I need to get and pass the current defined locale in symfony2 parameters.ini into the twig function, I define a global twig value:
twig:
globals:
locale: %locale%
And finally in twig template:
{{ currencySymbol(locale) }}

Resources