Overriding blocks within included Twig templates

前端 未结 5 953
北荒
北荒 2020-12-12 21:19

Is there a generally \"good\" way to achieve this functionality? I have read about the \'use\' tag, which seems like the best option so far, but I still don\'t like that it

5条回答
  •  感动是毒
    2020-12-12 21:36

    It can be done. Here's my solution to the problem by passing a variable to the view.

    #layout.twig
    {% if sidebar is empty %}
        This is the default sidebar text.
    {% else %}
        {% block sidebar %}{% endblock %}
    {% endif %}
    {% block content %}{% endblock %}
    
    #index.twig
    {% extends "layout.twig" %}
    {% block sidebar %}
        This is the sidebar. It will override the default text.
    {% endblock %}
    
    {% block content %}
        This is the content.
    {% endblock %}
    
    #index.php (SlimPHP)
    $app->render('index.twig', ['sidebar' => true]);
    

    Since I'm using SlimPHP the way I call it is by passing sidebar variable to the the view. This can be extended further by using different variables passed to the view, so you can selected sidebar1, sidebar2 etc.

提交回复
热议问题