Twig: Include external Code from an SVG file
Asked Answered
V

7

17

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

Something like:

{% include 'my.svg' %}

that will result in:

<svg viewbox=".... />
Vlf answered 8/7, 2016 at 7:38 Comment(1)
If you place that file in your template folder, sureLeftwards
L
20

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/

Leslileslie answered 4/4, 2017 at 10:26 Comment(0)
I
12

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

{{ source(directory ~ '/images/my.svg') }}
Imbrication answered 25/10, 2017 at 11:49 Comment(0)
E
11

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

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

Edra answered 21/12, 2016 at 11:26 Comment(0)
C
3

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, output using raw filter, or else it will escape the SVG markup:

{{ some_svg|raw }}
Chindwin answered 24/8, 2017 at 16:25 Comment(0)
D
2

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.

Depreciatory answered 26/11, 2019 at 21:17 Comment(0)
O
0

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 }}
Ocrea answered 11/8, 2016 at 12:53 Comment(0)
F
0

This worked for me in Drupal 9:

{% include active_theme_path() ~ '/images/sprite.svg' %}
Forsaken answered 26/6, 2023 at 14:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.