How to prevent this code duplication? - Twig - symfony

I use this piece of code in a big part of my templates:
{% if app.session.hasFlash('error') %}
<div class="error">
{{ app.session.flash('error') }}
</div>
{% endif %}
but the word error is changing. Could you give me idea how to avoid code duplication?
With include or macro I can change only the div class, but what about the word error in app.session.flash? And is there sense in doing this, or it's better to leave it that way?

You can include this with the "with" option. For example:
{% include 'AcmeDemoBundle:Tools:flash.html.twig' with {'flash':'error'} %}
And then in flash.html.twig do:
{% if app.session.hasFlash(flash) %}
<div class="{{flash}}">
{{ app.session.flash(flash) }}
</div>
{% endif %}

Related

Twig Runtime Error: Impossible to invoke a method ("test") on a string variable

I have the following twig template (the code is in the same file):
{% macro renderJob(fields) %}
// renders the job UI block, but I've removed it for simplicity
Hello world.
{% endmacro %}
{% block _jobs_widget %}
<div id="jobsContainer">
{% for fields in form.children %}
{% dump fields %}
{{ _self.renderJob(fields) }}
{% endfor %}
</div>
{% endblock %}
For some reason, after upgrading to twig/twig = v2.1.0 I'm receiving the follwing error:
Impossible to invoke a method ("renderJob") on a string variable ("#AppBundle/Jobs/form/job.html.twig").
I have been trying to figure out what's causing this without any luck. This used to work just fine in 1.3.x. The fields variable contains the proper data, but it appears it can't pass it to the renderJob macro or it can't find the macro (which is kind of odd)?
Have you tried the following ?
{% import _self as renderJobMacro %}
{% macro renderJob(fields) %}
// renders the job UI block, but I've removed it for simplicity
Hello world.
{% endmacro %}
{% block _jobs_widget %}
<div id="jobsContainer">
{% for fields in form.children %}
{{ renderJobMacro.renderJob(fields) }}
{% endfor %}
</div>
{% endblock %}
I think _self is depricated from twigg 2.0, May be you need to check without _self.
Check {{ renderJob(fields) }} instead of {{ _self.renderJob(fields) }}

Symfony Twig customize an Individual field for a collection

In the documentation there is a way in Symfony to customize a Individual field, based on the name/id of the widget.
{% form_theme form _self %}
{% block _product_name_widget %}
<div class="text_widget">
{{ block('field_widget') }}
</div>
{% endblock %}
{{ form_widget(form.name) }}
Here, the _product_name_widget fragment defines the template to use for the field whose id is product_name (and name is product[name]).
This works for a normal widget, but not if a widget is inside a collection. Because of the extra columns. Like this:
name="productbundle_product_type[foobar][1][value]" id="productbundle_product_type_foobar_1_value"
What is the way to make the Twig customization work inside the collection?
I thought something like this, but that doesn't work:
{% for db in edit_form.list %}
{% block _productbundle_product_type_foobar_{{ db.name }}_widget %}
<div class="text_widget">
{{ block('field_widget') }}
</div>
{% endblock %}
{% endfor %}
Even the following doesn't work:
{% _productbundle_product_type_foobar_1_value_widget %}
What is the way to make it work?
I was working on a project a couple of evenings ago and encountered precisely this problem - the solution I found is a pair of blocks that look like this (stripped of project-specific code):
{# Collection markup #}
{% block my_collection_widget %}
{# Customise collection row prototype for allow_add #}
{% if prototype is defined %}
{% set data_prototype = block('my_collection_item_widget') %}
<div id="my_prototype" data-prototype="{{ data_prototype }}" style="display: none"></div>
{% endif %}
{% for prototype in form %}
{{ block('my_collection_item_widget') }}
{% endfor %}
{% endblock my_collection_widget %}
{# Collection row markup #}
{% block my_collection_item_widget %}
{# Collection contains simple, single type #}
{{ form_errors(prototype) }}
{{ form_label(prototype) }}
{{ form_widget(prototype) }}
{# OR #}
{# Collection contains a compound type, render child types independantly #}
{{ form_errors(prototype.inner_widget) }}
{{ form_label(prototype.inner_widget) }}
{{ form_widget(prototype.inner_widget) }}
{% endblock my_collection_item_widget %}
I know this is old question, but maybe people still happening upon this. This is explained fragment naming for collections.
You use _entry_ in these cases in place of the collection element number. Use the instructions in the link for fragment naming, but this might vary. Sometimes 'type' is part of the fragment's name, sometimes first letter is upper case, sometimes lower case, etc. I would use a browser developer tool to find the actual name to make sure. You might also be able to customize the names used by adding the getBlockPrefix function to the form class.
Therefore, in your case above, the customized block might look something like:
{% block _ProductBundle_product_entry_widget %}
<div> {{ form_row(form.field)}} </div>
{% endblock %}
Where 'field' would be the name of a field in the element of your collection.
A few things here:
1. Documentation Error
The docs seem to be a bit off with CamelCase entities. As for 5.3 it should be: _taskManager_taskLists_entry_widget (instead of _task_manager_task_lists_entry_widget)
You can confirm the naming by dumping the form or form field: {{ dump(form) }} or {{ dump(form.yourField) }} in your template and then look for unique_block_prefix within the vars section.
2. Do NOT use the block overrides, macros are much more easy
It makes things absolutely more complicated than necessary. Simply define a macro:
{% import _self as formMacros %}
{% macro formatCollection(form) %}
<div class="form-group row">
<div>
{{ form_widget(form.field1) }}
{{ form_widget(form.field2) }}
{{ form_widget(form.field3) }}
</div>
</div>
{% endmacro %}
then simply run it on each collection:
{% for item in form.collectionItems %}
{{ formMacros.formatCollection(item) }}
{% endfor %}
3. Prototype
Get the prototype before rendering the collection field. You can store it in a variable.
{% set prototype = form.collection.vars.prototype %}
Then simply render it whenever you like using our macro:
<div data-js="collection" data-prototype="{{ formMacros.formatCollection(prototype)|e('html_attr') }}">

Symfony2, Twig, change twig after include

I have such hierarchy of twig files
my main (for controller) twig
{% extends "MainSiteBundle::layout.html.twig" %}
{% block footer_moderator_buttons %}
some buttons
{% endblock %}
{% block content_body %}
<p>hello moderator</p>
{{ include ('MainBlogBundle:_parts:postList.html.twig', {'postList': aPostDraft}) }}
{% endblock %}
postList.html.twig
<div class="post-list">
{% for postSingle in postList %}
{{ include ('MainBlogBundle:_parts:postSingle.html.twig', {'postSingle': postSingle}) }}
{% endfor %}
</div>
postSingle.html.twig
<div class="post">
<div class="post-header">
<a class="title" href="3">{{ postSingle.title }}</a>
</div>
<div class="post-meta">
<div>Date: {{ postSingle.date|date('D M Y') }}</div>
<div>Category: {{ postSingle.getCategory.getTitle }}</div>
<div>Author: {{ postSingle.getUser.username }}
</div>
</div>
<div class="post-body">
<div class="content">
<img width="450" height="200" src="#">
<div class="text">{{ postSingle.content }}</div>
</div>
</div>
<div class="post-footer">
{% block footer_moderator_buttons %}f{% endblock %}
<div>Views: 152</div>
<div>Comments: 1231</div>
<div>
<a class="link" href="#">More... </a>
</div>
</div>
</div>
As you can see last (postSingle.html.twig) has block "footer_moderator_buttons", so how can i change it from main twig (first one) ? Current is not working, what I need change \ do ?
In Twig 1.8 there is embed tag (http://twig.sensiolabs.org/doc/tags/embed.html).
You would have to remove the postList.html.twig file or work around it.
{% embed "MainBlogBundle:_parts:postSingle.html.twig" with {'postSingle': postSingle} %}
{% block footer_moderator_buttons %}
custom buttons here
{% endblock %}
{% endembed %}
So, you question is actually "I want to understand how\what twig can". Well, the answer to that question is: "It can't overwrite blocks from "main" to the smaller ones."
If you want to use twig, you have to stop thinking in php include() way where you make new files and you "PUT" components in them over and over again, components such as header, footer, menu etc.
In twig, you define main twig file with blocks which can be imagined as empty spaces which can, but do not have to, be overwritten. Surely, it still means you can have postList.html.twig as include in some file that extends MainSiteBundle::layout.html.twig. The same goes for postSingle.html.twig.
I think you catch the logic of twig except don't try to overwrite blocks from the wrong side - in this case, from MainSiteBundle::layout.html.twig to it's smaller portions.
how about this:
{% extends "MainSiteBundle::layout.html.twig" %}
....
{% block footer_moderator_buttons %}
{{ parent() }}
{% endblock %}
woops didnt put parent..
the {{ parent() }} will inherit {% block footer_moderator_buttons %}{% endblock %} from extended twig.

Maximum function nesting when extending twig template for sonata admin

I am using the following template to extend specific widget
{% use 'SonataAdminBundle:Form:form_admin_fields.html.twig' %}
{% form_theme form _self %}
{% block textarea_widget %}
{% spaceless %}
<div class="textarea_widget">
<textarea {{ block('widget_attributes') }}>{{ value|raw }}
</textarea>
</div>
{% endspaceless %}
{% endblock textarea_widget %}
The main problem is that it's reaching maximum function nesting. There must be some infinite recursion when extending template. When i copied code from extended template everything works. Any idea how to make this working?
This is probably caused by xDebug that you must configure with xdebug.max_nesting_level parameter. Default is 100 but I usually upgrade it to 1000 to be quiet.
On a Debian, it's in /etc/php5/conf.d/xdebug.ini.
Official doc about this parameter:
xdebug.max_nesting_level Type: integer, Default value: 100
Controls the protection mechanism for infinite recursion protection.
The value of this setting is the maximum level of nested functions
that are allowed before the script will be aborted.
to fix this error i needed to create form_admin_fields.html.twig file in app/Resources/SonataAdmin/views/Form with the following content:
{% block textarea_widget %}
{% spaceless %}
<div class="textarea_widget">
<textarea {{ block('widget_attributes') }}>{{ value|raw }} </textarea>
</div>
{% endspaceless %}
{% endblock %}
So there is no necessity to use or extend template just redefine some block.

Overwriting a field of AdmingeneratorGeneratorBundle

I am trying to overwrite a field of the AdmingeneratorGeneratorBundle and want to append a link to a certain field. That works quite well following the documentation:
{% extends_admingenerated "MyMainBundle:PageEdit:index.html.twig" %}
{% block form_status %}
{{ parent() }}
Preview
{% endblock %}
What I would need to do now, is to get the real id of my page instead of the static 8, but i could not figure out, what the object is called inside the twig template. Any ideas?
Update:
In my case, as I only need the ID of my page, I can use app.request.attributes.get('pk') to get it in twig. Would be interesting how to get other values tough.
Just use
{% extends_admingenerated "MyMainBundle:PageEdit:index.html.twig" %}
{% block form_status %}
{{ parent() }}
Preview
{% endblock %}
Cedric
The Documentation has been updated.
Thats ho it works:
{% extends_admingenerated "NamespaceYourBundle:List:index.html.twig" %}
{% block list_td_column_title %}
<span style="font-weight:bold">{{ Movie.title }}</span>
{% endblock %}

Resources