PRO: Basic twig-Syntax
Twig, Symfony
The PRO JCI-Plugin comes with the twig-Parser: With that, you have a simple programming language for using it together with JSON data. The basic syntax is described here: https://twig.symfony.com/doc/3.x/
Try it: twigfiddle
At https://twigfiddle.com you can get familiar with it, give it a try with twig-code
{{a}}
and this JSON (Select Format JSON
):
{"a": "this is a"}
and hit run. This should display this is a
for, if, matches
Let’s try this JSON with a list of two:
{"list" : [ "this is a", "this is b" ] }
with that twig code:
{% set tmp = "a" %} {% for l in list %} {{loop.index}}: {% if l matches '/'~tmp~'/' %} there is a match: {{l}} {% else %} "{{l}}" is not matching "{{tmp}}" {% endif %} {% endfor %}
Let’s go into the code details:
{% set tmp = "a" %}
defines a variable named tmp
{% for l in list %}...{% endfor %}
loops through the JSON-list
{{loop.index}}
is displaying the current iteration of the loop
{% if l matches '/'~tmp~'/' %}...{% else %}...{% endif %}
checks if the value of “l” (the current item of the loop) matches the value of “tmp”. The ‘~’ concats the value of “tmp” to a regular expression.
A bit simple would be: {% if l==tmp %}...{% else %}...{% endif %}
Read more on that at https://twig.symfony.com/doc/3.x/tags/for.html