Twig: Include external Code from an SVG file

前端 未结 6 1140
臣服心动
臣服心动 2021-01-02 03:05

Is it possible to inlcude code from a svg file directly into a twig template file?

Something like:

{% include \'my.svg\' %}

that wi

6条回答
  •  隐瞒了意图╮
    2021-01-02 03:41

    The twig function source() works fine in Drupal. I am not sure if it's better to use source() or include, but the Symfony docs recommend using the include() function rather than the directive. https://twig.symfony.com/doc/3.x/tags/include.html

    I also find it helps to add the theme namespace, which tells Twig to look in the templates directory.

    Assuming:

    • template file is themes/custom/theme_name/templates/some-template.html.twig
    • svg file is themes/custom/theme_name/templates/svg/sprite.svg
      {{ source('@theme_name/svg/sprite.svg') }}
    {# or #}
      {% include '@theme_name/svg/sprite.html.twig' %}
    {# or #}
      {{ include('@theme_name/svg/sprite.html.twig') }}
    

    This should also work for module templates as well as theme templates.

    I would think there is a performance benefit to using source() since the contents aren't parsed, but if you wanted a dynamic SVG, you should probably go the include() route.

提交回复
热议问题