How to include a reusable widget in Symfony (Twig)? - symfony

So, I'm still fairly new to Symfony and Twig. I was wondering how to best include/create a snippet of reusable code in the templates. Say, for example, that you have a sidebar that you want to show on every page.
{% extends 'AppBundle::base.html.twig' %}
{% block body %}
<div id="wrapper">
<div id="content-container">
{# Main content... #}
</div>
<div id="sidebar">
{% include 'sidebar.html.twig' %}
</div>
</div>
{% endblock %}
And that in that sidebar are a couple of widgets that all do their own logic. How you do go about creating/including those widgets?
So far, I've come across several solutions.
As a controller
The first was to embed the widget as a controller(s) in Twig.
class WidgetController extends Controller
{
public function recentArticlesWidgetAction()
{
// some logic to generate to required widget data
// ...
// Render custom widget template with data
return $this->render('widgets/recentArticles.html.twig', array('data' => $data)
);
}
public function subscribeButtonWidgetAction()
{
// ...
return $this->render('widgets/subscribeButton.html.twig', array('data' => $data)
}
// Many more widgets
// ...
}
And include that in 'sidebar.html.twig' like so
<div id="sidebar">
{# Recent Articles widget #}
{{ render(controller('AppBundle:Widget:recentArticlesWidget' )) }}
{# Subscribe-Button widget #}
{{ render(controller('AppBundle:Widget:subscribeButtonWidget' )) }}
{# and so on #}
</div>
As a service
I've also seen some people register widgets as services (that can be used in Twig directly). With the widget main class
// src/AppBundle/Service/RecentArticlesWidget.php
namespace AppBundle\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RecentArticlesWidget
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getRecentArticles()
{
// do some logic (use container for doctrine etc.)
}
}
that is then registered as a service,
# src/AppBundle/Resources/config/services.yml
services:
recentArticlesWidget:
class: AppBundle\Service\RecentArticlesWidget
arguments: ["#service_container"]
passed to the template in the controller,
namespace AppBundle\Controller;
class SidebarController {
public function showAction($request) {
// Get the widget(s)
$recentArticlesWidget = $this->get('recentArticlesWidget');
// Pass it (them) along
return $this->render('sidebar.html.twig', array('recentArticlesWidget' => $recentArticlesWidget));
}
}
so it can simply be used like this in Twig
{# sidebar.html.twig #}
{{ recentArticlesWidget.getRecentArticles()|raw }}
Alternatively, you can also add your service to the Twig global variables directly by adding it to the Twig config. This way, it won't need to be passed into the view by the controller.
#app/config/config.yml
twig:
globals:
# twig_var_name: symfony_service
recentArticlesWidget: "#recentArticlesWidget"
As a Twig Extension
This one is very similar to using a service above (see the documentation). You create an a twig extension class that is almost identical to the service shown previously
// src/AppBundle/Twig/RecentArticlesWidgetExtension.php
namespace AppBundle\Twig;
class RecentArticlesWidgetExtension extends \Twig_Extension
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getFunctions()
{
return array(
"getRecentArticles" => new Twig_Function_Method($this, "getRecentArticles")
// register more functions
);
}
public function getRecentArticles()
{
// do some logic (use container for doctrine etc.)
}
// Some more functions...
public function getName()
{
return 'WidgetExtension';
}
}
Register that as a service with an added tag
# src/AppBundle/Resources/config/services.yml
services:
recentArticlesWidget:
class: AppBundle\Twig\RecentArticlesWidgetExtension
arguments: [#service_container]
tags:
- { name: twig.extension }
and simply use it like a global function in Twig
{# sidebar.html.twig #}
{{ getRecentArticles() }}
Thoughts
One thing I noticed is that with the last two methods is that the logic and the view don't seem to be seperated at all anymore. You basically write a widget function and have that function output the complete html for the widget. This seems to go against the modularity and patterns Symfony tries to enforce.
On the other hand, calling a distinct controller or controller action (with their own twig renders) for every single widget seems like it could take more processing than might be needed. I'm not sure if it actually slows anything down, but I do wonder if its excessive.
Long story short, is there a best practice for using reusable widgets in Symfony? I'm sure some of these methods can also be mixed, so I was just wondering how to best go about this.

Twig extension and Twig macro should point you in the right direction.
Use the macro for the view and extension for the business logic.
On a side note in your Twig extension example, it's probably a good idea to only pass in services that you are using instead of the whole service container.

I would rather use blocks and a parent template. Simply put, insert the side bar in the main layout and have all other templates that require the side bar
inherit from it.
Something like this:
layout.html.twig will be something like this:
{% block title}
// title goes here
{%endblock%}
<div id="wrapper">
<div id="content-container">
{% block pageContent %}
{% endblock %}
</div>
<div id="sidebar">
// Side bar html goes here
</div>
</div>
Now all pages will inherit from this layout.html.twig. Say for example a page called home.html.twig will be:
home.html.twig
{% extends 'AppBundle::layout.html.twig' %}
{% block title%}
// this page title goes here
{% endblock %}
{% block pageContent %}
//This page content goes here
{% endblock %}
You can add as many blocks as needed, for example css and js blocks for each page.
Hope this helps!

I think the simplest way is defining a block in a template and then extending that template to render blocks like so:
#reusable.html.twig
{% block reusable_code %}
...
{% endblock %}
And
#reused.html.twig
{% extends 'reusable.html.twig' %}
{{ block('reusable_code') }}
If you want more reusability than that or your block contains business logic or model calls a twig extension is the way to go

Related

symfony parent template controller

Is there a standard/preferred way in Symfony to pass common variables to the base template?
There are things that are on every page, like a username in the menu that I obviously don't want to have to remember to add for every controller.
My thought was to create a controller for the template and return the data. But wondering if there is something more built in to handle this.
return $this->render(
'#secured/account/profile.html.twig',
array('userForm' => $form->createView(),
'base' => call_base_layout_controller()
);
{# templates/account/profile.html.twig #}
{% extends '#secured/base.html.twig' %}
{% block body %}
{% endblock %}
I cannot find it in the current version docs but, as far as I know you can still access a lot directly from twig through the app twig variable defined automatically by the framework for every request https://symfony.com/doc/3.4/templating/app_variable.html
For example, you can get the current user's username as follows:
{{ app.user.username }}
app holds user, request, session, environment, and debug so you can put other values needed into the session or environment variables, and fetch/render those values directly in the template.
If the data that you want is related to the authenticated user, I would recommend what Arleigh Hix said
Otherwise you can create a class that extends AbstractExtension and fill it with your logic
Anything on this class can be accessed from all your twig pages
// src/Twig/AppExtension.php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('myGlobalData', [$this, 'myGlobalData']),
];
}
public function myGlobalData()
{
return "what ever you want ( ex: a query resualt..)";
}
}
Than on your twig template just call it like this
{{ myGlobalData() }}
Even if it retuns an array, u can access it.

reusable dynamic sidebar in Symfony 4 (Twig)?

I recently started using Symfony 4 and I am creating my first website with this wonderful framework right now.
I have a sidebar that should be displayed in about half of my routes and the content of the sidebar should be filled with some data from a database.
Currently I use DI in all this routes and pass the result of the injected repository to the template (which includes my sidebar.html.twig) for the route.
public function chalupaBatman(FancyRepository $repository)
{
$sidebarObjects = $repository->getSidebarObjects();
$this->render('controllername/chalupabatman.html.twig', [
'sidebarObjects' => $sidebarObjects,
]);
}
I am wondering if there is a way to avoid this for every route I define in my controllers.
So far I found this topic on stackoverflow.
The User Mvin described my problem in a perfect way and also provided some solutions.
However there is still no answer to "what is the best practice" part also the topic is from 2017; therefor, the way to solve this may have changed in Symfony 4.
I ended up with a TwigExtension solution. I'll describe how to achieve it and it would be great if you guys could provide some feedback.
Let me know if I produce massive overhead or miss something essential ;-)
Alright, first of all I created a TwigExtension via command-line
php bin/console make:twig-extension AppExtension
And then I modified the class to look like this:
<?php
namespace App\Twig;
use App\Repository\ArticleRepository;
use Psr\Container\ContainerInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension implements ServiceSubscriberInterface
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getFunctions(): array
{
return [
new TwigFunction('article_sidebar', [$this, 'getArticleSidebar'], ['needs_environment' => true, 'is_safe' => ['html']]),
];
}
public function getArticleSidebar(\Twig_Environment $twig)
{
$articleRepository = $this->container->get(ArticleRepository::class);
$archive = $articleRepository->myAwesomeLogic('omegalul');
return $twig->render('/article/sidebar.html.twig', [
'archive' => $archive,
]);
}
public static function getSubscribedServices()
{
return [
ArticleRepository::class,
];
}
}
In order to activate Lazy Performance so our Repository and the additional Twig_Environment doesn't get instantiated everytime when we use Twig
we implement the ServiceSubscriberInterface and add the getSubscribedServices-method.
Therefor, our Repo and Twig_Environment only gets instantiated when we actually call {{ article_sidebar() }} inside a template.
{# example-template article_base.html.twig #}
{% extends 'base.html.twig' %}
{% block body %}
<div class="row">
<div class="col-10">
{% block article_body %}{% endblock %}
</div>
<div class="col-2">
{{ article_sidebar() }}
</div>
</div>
{% endblock %}
Now I am able to define my templates for the article-routes like this:
{# example-template /article/show.html.twig #}
{% extends 'article_base.html.twig' %}
{% block article_body %}
{# display the article here #}
{% endblock %}

No more routes available after Twig's render() function

I’m facing a weird behavior from Symfony 2.5.5 (PHP 5.6.1), more specifically Twig. Here is a fragment of my template layout:
<nav>
{% render controller('SGLotteryGameBundle:Home:lastDraw') %}
<ol class="breadcrumb">
<li>{{ 'SuperWinner'|trans }}</li>
{% block bc %}{% endblock %}
</ol>
</nav>
This template worked fine until I added the render call. After that, Symfony reported:
An exception has been thrown during the rendering of a template
("Unable to generate a URL for the named route "sg_lottery_home" as such route does not exist.")
in /home/kevin/Prog/PHP/SG2/src/SG/Lottery/GameBundle/Resources/views/layout.html.twig at line 70.
Of course, the sg_lottery_home is defined and works well without the render block. If I comment the path generation of this route, the immediate next one fails. Routes before the tag are rendered without any issue.
Here is the SGLotteryGameBundle:Home controller:
<?php
namespace SG\Lottery\GameBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
class HomeController extends Controller
{
/**
* #Template
*/
public function indexAction()
{
return [];
}
public function lastDrawAction()
{
return new Response('Dummy');
}
}
I tried replacing {% render ... %} by {{ render(...) }}, without any change.
Important note: it only happens when I’m logged in.
Apparently, it was caused by JMSI18nRoutingBundle generating an error while retrieving the user's locale: the available locales were en and fr and the user's locale fr_FR. I have no idea how the {{ render(...) }} call interacted with that.

Is it good practice to put Edge Side Includes into my templates?

In our Symfony2 Application we render reusable blocks with render_esi. We have this kind of templates:
{% for products as product %}
<div class="product">
<h4>{{ product.name }}</h4>
<div class="ratings">
{{ render_esi(controller('AcmeDemoCommunityBundle:Rating:ratingStars', {
objectType: 'product',
objectId: product.id,
readOnly: true
})) }}
</div>
</div>
{% endfor %}
And of cause we use the render_esi also in the detail page of the product.
I would like to differentiate different types of blocks:
Blocks that renders other actions of the same controller.
Blocks that could be used across other parts of the application.
What is the difference?
Blocks that only renders other actions of the same controller as the parent template are most of the times there to modularize one page and make parts cacheable. This blocks are only used one times in the whole application.
Blocks that renders parts like rating stars or comments are kind of independent widgets that provide an specific functionality. The current controller dose not know anything about this widgets. This kind of blocks are mostly used multiple times in an application.
What does that mean for the software design?
It means that we may want to change the way comments and ratings work in the future. May the not get rendered by an ESI anymore in the future because we have outsourced the functionality to an third-party service and only need to include some kind of JavaScript in this place? Or we render them directly?
This is something that has to be decided by the widget and not by the part that include the widget.
So what could I do to improve my design?
You could keep using ESI (because it makes sense for your usecase), but you should change the way of how the modules are included in the Twig files. You should move the logic for this out of the template into an separate Twig Extension in the AcmeDemoCommunityBundle.
namespace Acme\DemoCommunityBundle\Twig;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Acme\DemoCommunityBundle\Rating\RateableInterface;
class CommunityExtension extends \Twig_Extension
{
/**
* #var string
*/
const RATING_ACTION = 'AcmeDemoCommunityBundle:Rating:ratingStars';
/**
* #var FragmentHandler
*/
protected $handler;
public function __construct(FragmentHandler $handler)
{
$this->handler = $handler;
}
public function getFunctions()
{
return array(
'community_rating' => new \Twig_Function_Method($this, 'communityRating', array('is_safe' => array('html'))),
);
}
public function communityRating(RateableInterface $object, $readOnly = false)
{
return $this->handler->render(new ControllerReference(self::RATING_ACTION, array(
'objectType' => $object->getRatingType(),
'objectId' => $object->getId(),
'readOnly' => $readOnly
)), 'esi', $options);
}
public function getName()
{
return 'community';
}
}
services:
acme_community.twig.community:
class: Acme\DemoCommunityBundle\Twig\CommunityExtension
arguments: [ #fragment.handler ]
tags:
- { name: twig.extension }
Now your template should look like this:
{% for products as product %}
<div class="product">
<h4>{{ product.name }}</h4>
<div class="ratings">
{{ community_rating(product, true) }}
</div>
</div>
{% endfor %}
With this design it is easy to use the rating stars in our application, but we also have the flexibility to change the implementation how ratings work in the future without touching the templates where ratings are used.

Twig instanceof for inheritance objects

I am using the following feature from propel http://www.propelorm.org/documentation/09-inheritance.html.
I am also using Symfony2 and Twig
I have a class structure using the above feature that looks something like this
class Event {}
class Birthday extends Event {}
class Walking extends Event {}
now I pass an event object to a twig template and I want to know what type of event it is
For instance I want to display an image of a cake if its a birthday and I want to display map routes if its walking event.
I cannot use instanceof in Twig as this feature does not exist.
Does anyone now why this does not exist?
and is there a way I can replicate this functionality without having to do something like
public function getType()
in each class, or
public function isBirthday()
in the event class.
I found this on github but it is of no use to me. I have commented on their to see if I can get an answer.
https://github.com/fabpot/Twig/issues/553
I share the opinion, that instanceof is nothing that should appear in a template. I use twig-tests for this case
class MyTwigExtension extends TwigExtension
{
public function getTests ()
{
return [
new \Twig_SimpleTest('birthday', function (Event $event) { return $event instanceof Birthday; }),
new \Twig_SimpleTest('walking', function (Event $event) { return $event instanceof Walking; })
];
}
}
And in the template
{% if event is birthday %}{# do something #}{% endif %}
An indirect way of accomplishing this would be testing the object for a method, if you know each inherited object has a unique method. Maybe your Birthday class has a getBirthday(), while your Walking class has a getMap()?
{% if yourobject.methodName is defined %}
//Stuff that should only output when the object in question has the requested method
{% endif %}
Using instanceof in a template is frowned upon from an architectual standpoint. If you find yourself in a position where you "need" it, you have probably uncovered a problem in your architecture. Your getType solution in your case is probably the best. You could still put that into the event base class and read it out the name of the implementing class.
Another solution :
class Event {
...
public function isInstanceOfBirthday() {
return $this instanceof Birthday;
}
}
then it will works with any class that inherit from
class Birthday extends Event {}
class Walking extends Event {}
then in your twig :
{{ event.isInstanceOfBirthday ? ... something for Birthday instance ... : ... something for Walking instance ... }}
OR
{% if event.isInstanceOfBirthday %}
... do something for Birthday instance ...
{% else %}
... do something for Walking instance ...
{% endif %}
I'm trying to make an index.html.twig that lists entities that are defined by the user, and only the fields that have been marked as 'addToListing' So I get to the point in which I don't know what I'm printing.
{% for entity in entities %}
<tr>
{% for heading in headings %}
<td>{{ attribute(entity, heading) }}</td>
{% endfor %}
</tr>
{% endfor %}
And heading happens to be a \DateTime :/ So for such case I'd need to | date('format') or some better solution.
Any advise on a clean solution for me?
I had similar problem, it was related to the inheritance in Hotel software. I had a base class "RoomEquipment", and inheritance with "Bed", "ElectricAppliances"....
class BaseRoomEquipment {}
class Bed extends BaseRoomEquipment {}
class ElectricAppliances extends BaseRoomEquipment {}
And of course, a class "Room" with relation OneToMany towards RoomEquipment.
On template, I wanted to render beds only, but Room has relation to base equipment, which includes beds and electric appliances.
Instead of testing in twig template, in Room class i have created a method getBeds, and thats it.
class Room {
private $equipment;
public getBeds()
{
$res = [];
foreach($this->getEquipment() as $eq) {
if ($eq instanceof Bed) $res[] = $eq;
}
return $res;
}
// Rest of class here....
}
And, of course, in Twig:
<div>
{% for Bed in Room.beds %}
{{ Bed.nbPersons }}
{% endfor %}
</div>
Thanks to Property Accessor component - this is possible. Now, your twig does not have to check about instance type, nor it does no

Resources