Twig中的变量变量

时间:2018-01-18 11:05:38

标签: twig

我正在尝试使用Twig中的哈希来编写具有1级子菜单的菜单。我的代码是:

{% set regiones = {
patagonia:    { title: "Patagonia"},
pampa: { title: "Pampa"},
cuyo:     { title: "Cuyo"},
noreste:     { title: "Noreste"},
noroeste:     { title: "Noroeste"}
} %}

{% set patagonia = {
neuquen:    { title: "Neuquén"},
rionegro: { title: "Río Negro"},
chubut:     { title: "Chubut"},
santacruz:     { title: "Santa Cruz"},
tierradelfuego:     { title: "Tierra del Fuego"}
} %}

{% set pampa = {
buenosaires:    { title: "Buenos Aires"},
cordoba: { title: "Córdoba"},
lapampa:     { title: "La Pampa"},
santafe:     { title: "Santa Fe"}
} %}

{% set cuyo = {
mendoza:    { title: "Mendoza"},
sanjuan: { title: "San Juan"},
sanluis:     { title: "San Luis"}
} %}


<nav>
   <ul>
      {% for slug, item in regiones %}
         <li><a href="/{{ slug }}">{{ item.title }}</a>
            <ul>
               {% for slugg, itemm in {{ slug }}  %}
                  <li><a href="/{{ slugg }}">{{ itemm.title }}</a></li>
               {% endfor %}
            </ul>
         </li>
      {% endfor %}
   </ul>
</nav>

这一行:“{%for slugg,itemm in {{slug}}%}”不起作用。 我怎么能在twig中写一个变量变量,比如PHP中的$ {$ slug}?

谢谢, 米克尔

1 个答案:

答案 0 :(得分:1)

_context保存当前上下文中的变量,因此您可以执行以下操作:

{% for slugg, itemm in _context[slug] %}

由于您尚未设置变量norestenoroeste,因此您需要使用for块包围if块(否则Twig将抛出异常{{{ 1}}没有密钥_contextnoreste):

noroeste

See TwiggFiddle

另一种方法是将城市设置为新的哈希,如下所示:

{% if _context[slug] is defined %}
    <ul>
        {% for slugg, itemm in _context[slug] %}
            <li><a href="/{{ slugg }}">{{ itemm.title }}</a></li>
        {% endfor %}
    </ul>
{% endif %}

然后像这样修改你的循环:

{% set cities = {
    patagonia: {
        neuquen:        { title: "Neuquén"},
        rionegro:       { title: "Río Negro"},
        chubut:         { title: "Chubut"},
        santacruz:      { title: "Santa Cruz"},
        tierradelfuego: { title: "Tierra del Fuego"}
    },

    pampa: {
        buenosaires: { title: "Buenos Aires"},
        cordoba:     { title: "Córdoba"},
        lapampa:     { title: "La Pampa"},
        santafe:     { title: "Santa Fe"}
    },

    cuyo: {
        mendoza: { title: "Mendoza"},
        sanjuan: { title: "San Juan"},
        sanluis: { title: "San Luis"}
    }
} %}

还有一种方法是将地区和城市放在同一个哈希中:

{% if cities[slug] is defined %}
    <ul>
        {% for slugg, itemm in cities[slug] %}
            <li><a href="/{{ slugg }}">{{ itemm.title }}</a></li>
        {% endfor %}
    </ul>
{% endif %}