How to include a reusable widget in Symfony (Twig)?

六月ゝ 毕业季﹏ 提交于 2019-12-05 05:01:37

I think the simplest way is defining a block in a template and then extending that template to render blocks like so:

#reusable.html.twig

{% block reusable_code %}
  ...
{% endblock %}

And

#reused.html.twig
{% extends 'reusable.html.twig' %}

{{ block('reusable_code') }}

If you want more reusability than that or your block contains business logic or model calls a twig extension is the way to go

Twig extension and Twig macro should point you in the right direction.

Use the macro for the view and extension for the business logic.

On a side note in your Twig extension example, it's probably a good idea to only pass in services that you are using instead of the whole service container.

I would rather use blocks and a parent template. Simply put, insert the side bar in the main layout and have all other templates that require the side bar inherit from it.

Something like this:

layout.html.twig will be something like this:

{% block title}
// title goes here
{%endblock%}

<div id="wrapper">
    <div id="content-container">
        {% block pageContent %}
        {% endblock %}
    </div>
    <div id="sidebar">
        // Side bar html goes here
    </div>
</div>

Now all pages will inherit from this layout.html.twig. Say for example a page called home.html.twig will be:

home.html.twig

{% extends 'AppBundle::layout.html.twig' %}

{% block title%}
// this page title goes here
{% endblock %}

{% block pageContent %}
    //This page content goes here
{% endblock %}

You can add as many blocks as needed, for example css and js blocks for each page.

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!