Quick reference handbook
Here are some examples to quickly get you started.
How to…
- …create a fragment controller for a content element/frontend module and use variant templates?
- …render a dynamic template from a controller extending the
AbstractFragmentController? - …add a custom attribute to all content elements?
Info
This list is far from being complete — if you are missing a typical scenario, please contribute it!
Examples
Fragment controller
We create a content element controller in this example. If you want to create a module, these work very similar: you
then need to useAbstractFrontendModuleController as the abstract base class, [#AsFrontendModule] as the attribute
and frontend_module/_base.html.twig as the parent template, instead. If you want to make DCA adjustments, also target
tl_module instead of tl_content.
Create a src/Controller/FruitSaladController.php controller that renders a template with some fruits as parameters:
Create or adjust the contao/dca/tl_content.php file, so that there is something to see in the back end when editing
a fruit_salad element:
Create a content_element/fruit_salad.html.twig template:
Create a content_element/fruit_salad/random.html.twig variant template — here we want to output the fruits as a
randomized list instead of a block of text:
Dynamically render templates
Sometimes you might want to dynamically decide which template you want to render from inside your fragment controller.
There are two ways of doing it, by using the given FragmentTemplate or by calling render() yourself. For brevity, we
only focus on the implementation of the getReponse() method.
Setting the template name
Calling render() yourself
Note
When calling $template->getResponse(), internally, $this->render(null, $template->getData()) will get executed — by
using null as the first argument, our abstract controller class will use the inferred default template name. This
makes both variants effectively equivalent.
Adjust the base template
We want to add a custom data attribute that contains the element’s ID (e.g. data-element="42") to the div, that wraps
each content element. Overwriting the content_element/_base.html.twig is the way to go. For this example, we don’t
even have to adjust a block. The way HtmlAttributes are set up, it is enough to extend from the original template and
define our own attribute.
Tip
If you would need more data, that was not set by the abstract base class, you could create your own filter or function and then either use the element’s ID as an argument or make the filter/function context-aware, to get the information to your template.