Using Drupal 8, I have a media field where someone can upload an SVG file. I have this field display set to output as the URL path to the file.
I'm trying to get this value as a string (currently it's a render array) so I can call it with {% include var %} and embed the SVG directly into the DOM.

For example, I have this code. (I'm using twig_field_value.)

{% set var = content.field_media_name|field_value %}

If I render the variable in the template with {{ var }}, it spits out a string onto the screen, for example /sites/default/files/pathto/file.svg.

If I manually copy-paste this string into my twig template, e.g. {% include '/sites/default/files/pathto/file.svg'%}, it works perfectly, just like I want. However, I want to use {% include var %}, which is causing a PHP error because it can't include a template file because the var is actually an array.

This field can only have a single value. What I need is figuring out how to convert this into an actual string so I can use it with include.

  • You can access the string value of the array if you know the key which holds the value. You can figure that out by dumping the render array. – johndevman Jun 2 '17 at 8:11

This works:

{% include file_url(content.field_media_name|field_target_entity.field_file_upload.entity.uri.value) %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.