简体   繁体   中英

Symfony Twig Path function parameters, key defined by string

In Twig with Symfony, to generate a path in a template, it wants to use

{{ path('mypathname', {parameterName: parameterValue}) }}

In my project I have an inherited template, and one block loops through a chunk of data and spits out a list of URL's. What I want to do, is from my new template, is allow me to {% set %} the keyname of the first parameter

so basically like this

template.html.twig

<ul>
{% for thing in things %}
    <li><a href="{{ path(path_name, {path_param: thing.value}) }}">{{ thing.name }}</a></li>
{% endfor %}
</ul>

otherthings.html.twig

{% extends 'template.html.twig' %}
{% set path_name = "thingDetail" %}
{% set path_param = "id" %}

and see the output like

<ul>
    <li><a href="/things/detail?id=20">The 20th Thing</a></li>
</ul>

It may sound ridiculous, but across this app, the naming and pathing styles doesn't always match up with the different kinds of content that goes into that blocks loop, so some type of override needs to happen and the last thing I want to do right now, is overwrite the block for that for each type, when the last thing that needs to be done is URL generation

Thank you!

If you enclose the hash key in parenthesis, Twig will treat it as an expression:

{%- set field = 'foo' -%}
{%- set arr = { (field): 'bar' } -%}

will set arr to

{ foo: 'bar' }

(This is mentioned in the Twig documentation , but it's easy to see how it could be overlooked.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM