With twig how to store a variable inside html code - twig

Is there an equivalent to this in Twig :
<?php
$a = 'hello';
$b = '<h1>'.$a.'</h1>';
echo $b;
?>
I try this but without success :
{% set a = 'hello' %}
{% set b = <h1>{{a}}</h1> %}
I'm new to twig and couldn't find a way to do this.

To concatenate in Twig you need the tilda symbol, ~
Eg.
{% set a = 'hello' %}
{% set b = '<h1>'~a~'</h1>' %}
Or you can use string interpolation
E.g.
{{ "<h1>{a}</h1>" }}

You can concatenate and dump with the raw filter:
{% set a = 'hello' %}
{% set b = '<h1>' ~ a ~ '</h1>' %}
{{ b|raw }}
Here a working solutions

Related

Access variable inside a loop and variable in Twig

I would like to do the following:
{% for i in 0..10 %}
{% if content_{{ i }}_raw == 2 %}
...
{% endif %}
{% endfor %}
Is it possible to get {{ i }} inside the variable content_1_raw and replace the 1 with the value of i?
Yes. The _context variable holds all variables in the current context. You can access its values with the bracket notation or using the attribute function:
{% for i in 0..10 %}
{% if _context['content_' ~ i ~ '_raw'] == 2 %}
...
{% endif %}
{# or #}
{% if attribute(_context, 'content_' ~ i ~ '_raw') == 2 %}
...
{% endif %}
{% endfor %}
I have written more details about this here: Symfony2 - How to access dynamic variable names in twig
Also, instead of writing 'content_' ~ i ~ '_raw' (tilde, ~, is string concatenation operator), you can also use string interpolation:
"content_#{i}_raw"

Ternary concatenation in Twig

Is it possible to use ternary operator in Twig when concatenating one string to another if some condition is true?
This works for me:
{% set a = 'initial' %}
{% if foo == bar %}
{% set a = a ~ ' concatenate' %}
{% endif %}
<p>{{ a }}</p>
But when I try to simplify it like this, it throws an error:
{% set a = 'initial' ~ (foo == bar) ? ' concatenate' : '' %}
<p>{{ a }}</p>
Am I doing something wrong or this simplification is simply not possible in Twig?
due to the order of precedence you'll need to add parentheses, {% set a = 'initial' ~ ((foo == bar) ? ' concatenate' : '') %}
If the 2nd part is empty you can even omit it e.g.
{% set b = 'initial' ~ ((foo == foo) ? ' concatenate') %}
twigfiddle

how to subtract dates in twig?

{%for mat in setQuery %}
{% set datePost = mat.data_criacao|date('d-m-Y') %}
{% set today = "now"|date('d-m-Y') %}
{{today- datePost}}
{% endfor %}
datePost = 17-04-2015
today = 06-05-2015
the example above returns it: -11
The issue was resolved with the following code:
{% set datePost = mat.data_criacao|date('d-m-Y') %}
{% set today = "now"|date('d-m-Y') %}
{% set difference = date(today).diff(date(datePost))%}
{% set leftDays = difference.days %}
{% if datePost == today %}
1 day
{% else %}
{{ leftDays }}
{% endif %}
You must write your custom twig extension:
You must write a twig function as described here with the following code for make diff via php function:
$calcFrom = $from;
$calcTo = $to;
$now->diff($calcFrom)->format("%a")
And make it available via a Twig extension.
If you are using symfony2 framework You can use the KnpTimeBundle
In the Twig:
This compare with the current date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(form) }}
This compare with the another date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(form , to ) }}
Hope this help

Twig - Append string data to same variable

How would you append more data to the same variable in Twig? For example, this is what I'm trying to do in Twig:
var data = "foo";
data += 'bar';
I have figured out that ~ appends strings together in Twig. When I try {% set data ~ 'foo' %} I get an error in Twig.
The ~ operator does not perform assignment, which is the likely cause of the error.
Instead, you need to assign the appended string back to the variable:
{% set data = data ~ 'foo' %}
See also: How to combine two string in twig?
Displaying dynamically in twig
{% for Resp in test.TestRespuestasA %}
{% set name = "preg_A_" ~ Resp.id %}
{% set name_aux = "preg_A_comentario" ~ Resp.id %}
<li>{{ form_row(attribute(form, name)) }}</li>
{% endfor %}
You can also define a custom filter like Liquid's |append filter in your Twig instance which does the same thing.
$loader = new Twig_Loader_Filesystem('./path/to/views/dir');
$twig = new Twig_Environment($loader);
...
...
$twig->addFilter(new Twig_SimpleFilter('append', function($val, $append) {
return $val . $append;
}));
Resulting in the following markup:
{% set pants = 'I\'m wearing stretchy pants!' %}
{% set part2 = ' and they\'re friggin\' comfy!' %}
{% set pants = pants|append(part2) %}
{{ pants }}
{# result: I'm wearing stretchy pants! and they're friggin' comfy! #}
IMHO I find the above sample more intuitive than the ~ combinator, especially when working on a shared codebase where people new to the syntax might get a bit mixed up.

How to combine two string in twig?

I want to do something like this:
{% set c=a+b %}
Where a and b are strings.
How can I do it?
The way to do it is:
{% set c = a ~ b %}
Use the "~" operator. This will concatenate your two strings. The "+" operator cannot be used to combine strings.
You would get this:
{% set c=a~b %}
More info:
The "+" operator: Adds two objects together (the operands are casted to numbers).
You can use:
{{ "Hello " ~ name ~ "!" }}
A clearer example for the {% block page %}...{% endblock %}:
{% block page %}
{% set page = page | merge({
"title" : branchName,
"description" : "This description has "~branchName~" as its title"
}) %}
{{ parent() }}
{% endblock %}
A clearer example for the {% block content %}...{% endblock %}:
{% block content %}
This is just a sample string for {{ branchName }} that needs no concatenation
{% endblock %}

Resources