【问题标题】:Twig: Include external Code from an SVG fileTwig:包含来自 SVG 文件的外部代码
【发布时间】:2016-07-08 07:38:19
【问题描述】:

是否可以将 svg 文件中的代码直接包含到 twig 模板文件中?

类似:

{% include 'my.svg' %}

这将导致:

<svg viewbox=".... />

【问题讨论】:

  • 如果您将该文件放在模板文件夹中,请确定

标签: svg twig inline templating


【解决方案1】:

一种方法:

{{ source('my.svg') }}

在这里阅读更多: https://www.theodo.fr/blog/2017/01/integrating-and-interacting-with-svg-image-files-using-twig/

【讨论】:

    【解决方案2】:

    如果是主题,最好使用包含主题路径的{{ directory }} 变量。

    {{ source(directory ~ '/images/my.svg') }}
    

    【讨论】:

      【解决方案3】:

      有一个类似的问题,最终将我的 svgs 重命名为 .twig 文件。

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

      【讨论】:

        【解决方案4】:

        对我来说,它有效:

        {% include '/images/my.svg' %}
        

        如果您使用的是 Drupal 8,请快速更新一下,因为上一个答案中的代码对我不起作用。我就是这样做的:

        function theme_preprocess_page(&$variables) {
          $svg = file_get_contents(drupal_get_path('theme', 'theme_name') . '/images/my.svg');
          $variables['some_svg'] = $svg;
        }
        

        在 twig 文件中,使用raw 过滤器输出,否则它将转义 SVG 标记:

        {{ some_svg|raw }}
        

        【讨论】:

          【解决方案5】:

          twig 函数 source() 在 Drupal 中运行良好。我不确定使用 source() 还是 include 更好,但 Symfony 文档建议使用 include() 函数而不是指令。 https://twig.symfony.com/doc/3.x/tags/include.html

          我还发现添加主题命名空间很有帮助,它告诉 Twig 在模板目录中查找。

          假设:

          • 模板文件是themes/custom/theme_name/templates/some-template.html.twig
          • svg文件是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') }}
          

          这也适用于模块模板和主题模板。

          我认为使用 source() 对性能有好处,因为内容不会被解析,但如果你想要一个动态 SVG,你可能应该使用 include() 路由。

          【讨论】:

            【解决方案6】:

            您可以通过设置新变量在 Drupal8 主题中进行操作:

            function theme_preprocess_page(&$variables) {
              $svg = file_get_contents(drupal_get_path('theme', 'socialbase') . '/images/icons.svg');
              $variables['svg_sprite'] = t('svg', array('svg' => $svg));
            }
            

            在您的 twig 文件中,您可以使用以下命令进行打印:

            {{ svg_sprite }}
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-06-02
              • 1970-01-01
              • 2017-08-09
              • 2020-05-27
              • 2022-01-20
              • 2011-07-05
              • 1970-01-01
              相关资源
              最近更新 更多