How to call variable (Object)'s method in expression syntax? [Twig Templating] - php

How to call a variable's method in expression syntax in twig tempting system.
see the example below
{{ myObj.someMethod() }} {# this print the output of this method #}
i don't want above code because its printing output of this method.
but i want this
{% myObj.someMethod() %}
but its is giving me error that
Unknown tag name "myObj" in "
{% myObj.someMethod() %}" at line 2
even with above error method is also being called.

In twig syntax {{ some variable}} will print the result in variable you need to set variable and then use where you want
{% set myvar = myObj.someMethod() %} /* this will store the result returned from function */
{{ myvar }} /* this will print the result in myvar */

Related

Twig - Use variable key for object

I am using Twig and I have a problem.
I have a problem when I want to use a variable index for an object.
Here is my code:
{% for label, field in params.fields %}
{{ dump(data.field) }}
{% endfor %}
data is an object containing {'email': 'test#test.fr', 'name': 'John'}.
Field is an array of string containing ['email', 'name']
I can't show the value my object dynamically.
{{ dump(data.email) }} works.
How can I use dynamic indexes?
In Twig syntax, data.field is equal to $data['field'] in PHP. In other words, Twig use field as the array key name instead of taking the value of the field variable and use it as a key name.
If you want something similar to $data[$field], you can use the attribute() function:
The attribute function can be used to access a "dynamic" attribute of a variable:
Example:
{{ dump(attribute(data, field)) }}
{# or simply #}
{{ attribute(data, field) }}

Display split results in Symfony2 twig

I have a function in my Symfony controller which returns the following:
test+testString1+test2
TestController.php
public function getResultAction($fileName) {
$string1="test";
$string2="testString1";
$string3="test2";
$response = $string1."+".$string2."+".$string3;
return new Response($response);
}
In my twig I've rendered the function in my controller:
test.html.twig
{% set test %}
{{ render(controller('TestBundle:Test:getResult')) }}|split('+', 4)
{% endset %}
{{ test[0] }}
I'm using twig split filter so that I can display test, testString1 and test2 individually. But then whenever I attempt to display test[0], I receive the following error:
Impossible to access a key "0" on an object of class "Twig_Markup" that does not implement ArrayAccess interface in TestBundle:Test:test.html.twig
What's wrong with what I'm doing? I hope you could help me with this. Thanks
You miss the split filter inside the double brace as follow:
{% set test %}
{{ render(controller('TestBundle:Test:getResult')) |split('+', 4) }}
{% endset %}
Hovenever seems same problem with the set tag. From the doc:
The set tag can also be used to 'capture' chunks of text
Try with:
{%
set test=render(controller('TestBundle:Test:getResult'))|split('+', 4)
%}
Hope this help

Concatenation with dynamic variables for Twig symfony

I have a specific problem with concat of twig.
When I trying to concatenate dynamic variables showing the error.
Here is my code :
{% set i = 0 %}
{% set nbLignes = codeEvt.nb_lignes_~i %}
{% set nbLignesRef = codeEvt.nb_lignes_ref_~i %}
But I have this error message :
Method "nb_lignes_" for object "\DTO\SuiviJourFonc" does not exist in XXXXXXXXX.html.twig at line 211
I would like to take codeEvt.nb_lignes_0 , but i would like build a "for" for others variables like nb_lignes_1, nb_lignes_2 , nb_lignes_3 ...
How can i do this ?
attribute can be used to access a dynamic attribute of a variable:
The attribute function was added in Twig 1.2.
{{ attribute(object, method) }}
{{ attribute(object, method,arguments) }}
{{ attribute(array, item) }}
Try like this,
{{ attribute(codeEvt, 'nb_lignes_ref_' ~ i) }}
You can try the array-like notation:
{{ codeEvt['nb_lignes_ref_' ~ i] }}
Or even use string interpolation:
{{ codeEvt["nb_lignes_ref_#{i}"] }}

Symfony2 Array to string conversion, set empty value

I`am rendering a twig template in symfony2 and its possible to get a variable with value of array type but i am trying to preview the variable and this error pops:
Array to string conversion ...
So my qustion is not how to print out the array, but is it possible in twig to disable this error, so when an array comes and it cannot be outputed, to set an empty value.
In config.yml, under twig i have set
strict_variables: false
But this dose not include printing arrays.
EDIT:
In controller I pass this array to twig, for example:
'data' => array(
'description' => array(
'desc1',
'desc2'
)
);
In twig I am trying to print {{ data['description'] }} and I got the following error:
Array to string conversion ...
This is the normal error that must pop, but I need if I try to print this a no error to pop but instead I need to print nothing(empty value), same way like trying to print an non existing variable with twig set with
strict_variables: false
ANSWER:
Make a custom function:
public function getFunctions()
{
return array(
'to_string' => new \Twig_Function_Method($this, 'toString')
);
}
public function toString($data) {
if(is_array($data)) {
return '';
}
return $data;
}
And in twig template:
{{ to_string(data['description']) }}
You have two desc: desc1 and desc2, what do you want to print? If both you have to use this notation (for instance)
{{ data['description'][desc1] }} - {{ data['description'][desc2] }}
More in general:
{% for desc in data['description'] %}
{{ desc }}
{% endfor %}
EDIT
Ok, now I got it (from your comment):
{% if data['description'] is iterable %}
//echo here an empty string
{% else %}
{{ data['description'] }}
{% endif %}

Set variable in twig template then using it with another variable

I have the folowing long variable in Twig to read the src attribute of an image in RSS feed:
<img src="{{item.get_item_tags("http://www.w3.org/2005/Atom","link")[0]['child']['http://search.yahoo.com/mrss/']['content'][0]['child']['http://search.yahoo.com/mrss/']['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src']}}"/>
I want to make the code more cleaner and readable, so initially, I defined two variables to act as parameter of get_item_tags() and the other as a path for the array:
{% set param1 = 'http://www.w3.org/2005/Atom' %}
{% set arrayPath = '[0]['child']['http://search.yahoo.com/mrss/']['content'][0]['child']['http://search.yahoo.com/mrss/']['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src']' %}
What I want to get, but it generate error, is:
<img src="{{item.get_item_tags({{param1}}, "link"){{arrayPath}}}}" />
I don't use symfony and Twig version is 1.16.0
When you set a variable in twig and want to use it inside another function either in {{ }} or {% %} you do not need to use {{ }} again for the set variable.
Furthermore, you cannot set a variable as index of another variable then concat them; so you need to change it to:
{% set param1 = 'http://www.w3.org/2005/Atom' %}
{% set output = item.get_item_tags(param1, "link") %}
{% set yk = 'http://search.yahoo.com/mrss/' %}
<img src="{{ output[0]['child'][(yk)]['content'][0]['child'][(yk)]['thumbnail'][0]['child']['http://www.w3.org/2005/Atom']['img'][0]['attribs']['']['src'] }}" />

Categories