Call macros in a for loop - twig

Is it possible within twig to call a macro in a for loop by passing variables from the loop into the macro call?
For example:
{% for formElem in formElems %}
{{ forms.elem({{ formElem.type }}, {{ formElem.name }}, {{ formElem.value }}) }}
{% endfor %}
By the way, I know the above syntax doesn't work because I tried it and got an error, but nevertheless, is it possible to pass variables to a macro?

Try changing your syntax to this:
{% for formElem in formElems %}
{{ forms.elem(formElem.type, formElem.name, formElem.value) }}
{% endfor %}
You don't need to use the {{ }} to pass a twig variable to a twig macro

Related

Shopware : Impossible to extend through plugin user-detail

I have Shopware 6.5.3. I was trying to extend "sw-users-permissions-user-detail" like this :
import template from './sw-users-permissions-user-detail.html.twig';
Shopware.Component.override('sw-users-permissions-user-detail', {
template
});
And file 'sw-users-permissions-user-detail.html.twig'
{% block sw_settings_user_detail %}
{% parent %}
{% block test %}
<p>Blabla</p>
{% endblock %}
{% endblock %}
It's not working at all, and I don't know why.
Any help ?
NB : It's working when I'm overriding other templates :
Component.override('sw-dashboard-index', {
template
});
If you want to put the original contents to the block, that you are overriding, you should use the 'parent' statement like this:
{{ parent() }}

Symfony & Twig: how to get vars in twig by DB data?

One question please.
{{ dump(app.user.slugName) }}
If I do the above snippet in Twig, I get the slugName of the user loged ("my-user-2", i.e.) in the app (SlugName is an atribute of the entity user). Ok & Correct. But... I want to order this action from a var (var from BD data)
I have a variable named option which is set like this:
{% set option = 'app.user.slugName' %}
But when I'm trying output this variable with {{ dump(option)}} it returns app.user.slugName as literal. It does not return my-user-2.
Is there are any way in twig to solve this? It's a function to generate a menu, but some links needs some parameters.
I see what you mean, but Twig can't evaluate expression like that.
To achieve something like that you would need a snippet like this,
{% set value_methods = 'app.user.slugname' %}
{% set option_value = _context %}
{% for method in (value_methods|split('.')) if method != '' %}
{% set option_value = attribute(option_value, (method|replace({'()': '', }))) %}
{% endfor %}
{{ option_value }}
twigfiddle
(edit)
Remember you can create a macro to achieve some reusability for this snippet,
{% import _self as macros %}
{{ macros.evaluate(_context, 'app.user.slugname') }}
{% macro evaluate(context, value_methods) %}
{% set option_value = context %}
{% for method in (value_methods|split('.')) if method != '' %}
{% set option_value = attribute(option_value, (method|replace({'()': '', }))) %}
{% endfor %}
{{ option_value }}
{% endmacro %}

Twig get object names ending with numbers dynamically

I have some objects like address1, address2, address3 ... address10. All these objects have lat and long values.
I know we can get it from the attribute() function of Twig, but what I want in my twig template is to get the main objects
{% for i in 1..10 %}
{% set address = address~i %}
{{ address.lat }}
// or like
{{ attribute(address, 'lat') }}
{% endfor %}
Just simply use :
{% for i in 1..10 %}
{{ attribute(attribute(_context, 'address'~i), 'lat') }}
{% endfor %}

Check if variable is string or array in Twig

Is it possible to check if given variable is string in Twig ?
Expected solution:
messages.en.yml:
hello:
stranger: Hello stranger !
known: Hello %name% !
Twig template:
{% set title='hello.stranger' %}
{% set title=['hello.known',{'%name%' : 'hsz'}] %}
{% if title is string %}
{{ title|trans }}
{% else %}
{{ title[0]|trans(title[1]) }}
{% endif %}
Is it possible to do it this way ? Or maybe you have better solution ?
Can be done with the test iterable, added in twig1.7, as Wouter J stated in the comment :
{# evaluates to true if the users variable is iterable #}
{% if users is iterable %}
{% for user in users %}
Hello {{ user }}!
{% endfor %}
{% else %}
{# users is probably a string #}
Hello {{ users }}!
{% endif %}
Reference : iterable
Ok, I did it with:
{% if title[0] is not defined %}
{{ title|trans }}
{% else %}
{{ title[0]|trans(title[1]) }}
{% endif %}
Ugly, but works.
I found iterable to not be good enough since other objects can also be iterable, and are clearly different than an array.
Therefore adding a new Twig_SimpleTest to check if an item is_array is much more explicit. You can add this to your app configuration / after twig is bootstrapped.
$isArray= new Twig_SimpleTest('array', function ($value) {
return is_array($value);
});
$twig->addTest($isArray);
Usage becomes very clean:
{% if value is array %}
<!-- handle array -->
{% else %}
<!-- handle non-array -->
{% endif % }
There is no way to check it correctly using code from the box.
It's better to create custom TwigExtension and add custom check (or use code from OptionResolver).
So, as the result, for Twig 3, it will be smth like this
class CoreExtension extends AbstractExtension
{
public function getTests(): array
{
return [
new TwigTest('instanceof', [$this, 'instanceof']),
];
}
public function instanceof($value, string $type): bool
{
return ('null' === $type && null === $value)
|| (\function_exists($func = 'is_'.$type) && $func($value))
|| $value instanceof $type;
}
}
Assuming you know for a fact that a value is always either a string or an array:
{% if value is iterable and value is not string %}
...
{% else %}
...
{% endif %}
This worked good enough for me in a project I was working on. I realize you may need another solution.

Using twig variable to dynamically call an imported macro sub-function

I am attempting if use a variable to call a specific macro name.
I have a macros file that is being imported
{% import 'form-elements.html.twig' as forms %}
Now in that file there are all the form element macros: text, textarea, select, radio etc.
I have an array variable that gets passed in that has an elements in it:
$elements = array(
array(
'type'=>'text,
'value'=>'some value',
'atts'=>null,
),
array(
'type'=>'text,
'value'=>'some other value',
'atts'=>null,
),
);
{{ elements }}
what im trying to do is generate those elements from the macros. they work just fine when called by name:
{{ forms.text(element.0.name,element.0.value,element.0.atts) }}
However what i want to do is something like this:
{% for element in elements %}
{{ forms[element.type](element.name,element.value,element.atts) }}
{% endfor %}
I have tried the following all resulting in the same error:
{{ forms["'"..element.type.."'"](element.name,element.value,element.atts) }}
{{ forms.(element.type)(element.name,element.value,element.atts) }}
{{ forms.{element.type}(element.name,element.value,element.atts) }}
This unfortunately throws the following error:
Fatal error: Uncaught exception 'LogicException' with message 'Attribute "value" does not exist for Node "Twig_Node_Expression_GetAttr".' in Twig\Environment.php on line 541
Any help or advice on a solution or a better schema to use would be very helpful.
I just thought other people may want the answer to this, as provide by fabpot:
This is indeed something that is not supported: calling a macro with a dynamic name (I have added a proper exception to be clearer about the issue).
If you really want to do that, you can do so with the following code:
{{ attribute(forms, element.type, [element.name,element.value,element.atts]) }}
-fabpot
https://github.com/twigphp/Twig/issues/922#issuecomment-11133299
Dynamic macros may not be supported in Twig.
But there is a simple workaround since you can dynamically include other templates.
Example:
Let's say you have a bunch of content modules or content blocks (or however you wanna call them) for your site. And you have Twig macros responsible of rendering each of these modules.
{# modules.twig #}
{% macro module1(config) %}
<div>module one</div>
{% endmacro %}
{% macro module2(config) %}
<div>module two</div>
{% endmacro %}
{% macro module3(config) %}
<div>module three</div>
{% endmacro %}
Now, what you need to dynamically call these macros is to add an extra template for each, like so:
{# module1.twig #}
{% import "modules.twig" as modules %}
{{ modules.module1(config) }}
{# module2.twig #}
{% import "modules.twig" as modules %}
{{ modules.module2(config) }}
{# module3.twig #}
{% import "modules.twig" as modules %}
{{ modules.module3(config) }}
Finally, in your actual page template you just include the template instead of calling the macro.
{# template.twig #}
{# this is the macro's name to be called #}
{% set macro = 'module2' %}
{# this is just a config object to be passed to the macro #}
{% set config = {} %}
{% include macro ~ '.twig' with { config: config } only %}
Et voilá, (dynamically produced) output will be <div>module two</div>.

Resources