Twig: include external code from SVG file

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

Something like:

{% include 'my.svg' %} 

which will result in:

 <svg viewbox=".... /> 
+8
svg twig inline templating
source share
5 answers
+6
source share

Had a similar problem, eventually renamed my svgs to .twig files.

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

+4
source share

You can do in the Drupal8 theme by 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 }} 
+1
source share

In the case of a topic, a good opportunity is to use the {{ directory }} variable, which contains the path to the topic.

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

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 did not work for me. Here 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 output it like this:

 {{ some_svg|raw }} 
0
source share

All Articles