Twig变量的Twig增量值为1

时间:2017-02-16 17:05:55

标签: php symfony twig

我需要使用Twig root_path变量添加set body类。哪个打印每个页面字符串'节点'。

我如何编写条件,if root_path == 'node'增量值为1,因此它将1添加到字符串节点。对于每个页面增量node_1node_2node_3等等。

Twig对我来说是全新的,如果我现在不清楚也很抱歉。 试过这个,但我想这完全没有任何意义。

{% if root_path === 'node' %}

{% set root_path = root_path + 1 %}

{% endif %}

2 个答案:

答案 0 :(得分:1)

我不确切知道是否需要增加页面中变量root_path的数量。如果是这样,那么你必须通过一些字符串运算符。这是一种可能性:

  {% if root_path[0:4] == 'node' %}
  {% set root_path = 'node_' ~ (root_path|split('_', 2)[1] + 1) %}
  {% endif %}

  <p>{{ root_path }}</p> // show node_1

  {% if root_path[0:4] == 'node' %}
    {% set root_path = 'node_' ~ (root_path|split('_', 2)[1] + 1) %}
  {% endif %}

  <p>{{ root_path }}</p> // show node_2

如果您想在一边计算,请在会话中使用计数器。

但无论如何,请将字符串和索引的组合分开并在必要时将它们放在一起。

<body id=”{{ ‘node_’ ~ counter }}”>

答案 1 :(得分:0)

您应该通过展示包含页面的变量和预期标记的外观来澄清您的问题。

如果您的目标是遍历链接树以生成索引,您可能会对我开发的扩展感兴趣。

https://github.com/ninsuo/jordan-tree

{% tree item in menu %}
  {% if treeloop.first %}<ul>{% endif %}
    <li>
        <a href="{{ item.url }}">{{ item.name }}</a>
        {% subtree item.children %}
    </li>
  {% if treeloop.last %}</ul>{% endif %}
{% endtree %}
相关问题