Twig: Include external Code from an SVG file

爱⌒轻易说出口 提交于 2019-11-30 18:15:59

One way of doing this:

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

Read more here: https://www.theodo.fr/blog/2017/01/integrating-and-interacting-with-svg-image-files-using-twig/

LT86

Had a similar issue, ended up renaming my svgs to be .twig files.

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

You can do in a Drupal8 theme via setting a new variable:

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));
}

In your twig file you can print it with:

{{ svg_sprite }}

For me, it worked:

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

Just a quick update if you are using Drupal 8 because the code in the previous answer didn't work for me. This is how I did it:

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

And in the twig file I outputed it like this:

{{ some_svg|raw }}

In case of theme it's good option to use {{ directory }} variable that holds path to theme.

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