问题描述:

I have several "widgets" I use in Symfony form. These are datepicker field, colorpicker field, fancy combo box and the like. I keep the template for each one in separate Twig file, like so:

# start of color_widget.html.twig

{% block color_widget %}

<div id="{{ id }}" class="input-group colorpicker-component">

<span class="input-group-addon"><i></i></span>

<input type="text" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %} class="form-control" />

</div>

<script>

$(function() {

$('#{{ id }}').colorpicker();

});

</script>

{% endblock %}

# end of color_widget.html.twig

Now, in current setting I should keep all that blocks in one big template. But I'd like to make a loop to include the defined blocks from those separate files. In essence I'm attempting substituting this:

{% use "@CoreWidgets/color/widget.html.twig" %}

{% use "@CoreWidgets/date_picker/widget.html.twig" %}

{% use "@OtherWidget/widget.html.twig" %}

with something like this:

{% for widget in _widgets %}

{% use widget.path %}

{% endfor %}

But as use tag doesn't support variables it doesn't work.

I want such approach because I'd like to have nice widget packages - storing in one place CSS, JS, Twig templates (one for form element and the other for element of page showing the entity info). Then I could define that packages in a config file and have all neatly set and stored.

Is there any way to accomplish this?

网友答案:

It's not a great solution but you can include a file that contains a use statement for each widgets :

{# file 1 : file that calls the use tag : #}
{% use "@CoreWidgets/color/widget.html.twig" %}

Then include it the way you wanted :

{# file 2 : file that include it : #}
{% for widget in _widgets %}
    {% include widget.path %}
{% endfor %}

So the widget.path must store the path of the file 1.

相关阅读:
Top