Is it possible to change the fill or stroke colour of an SVG using a value pulled from a custom field? For example:

{{ svg('@webroot/_dist/stat/link-arrow.svg')|attr({
    stroke: '{{ entry.myCustomFieldValue }}'
}) }}

I can only get it to partially work by using a class but unfortunately there are a number of SVGs on the page so we'd also need to change all the class names :/ - and it's ugly!

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.3.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 37.9 20.1" style="enable-background:new 0 0 37.9 20.1;" xml:space="preserve">
<style type="text/css">
    .st0{fill:none;stroke:{{entry.myCustomFieldValue }};stroke-width:2;}
<g transform="translate(0 0.526)">
    <line class="st0" x1="0" y1="9.8" x2="36.5" y2="9.8"/>
    <g transform="translate(31.688 1)">
        <path class="st0" d="M-1-1l2.8,4.5l3.6,5.8"/>
        <path class="st0" d="M-1,18l2.4-3.8l0,0l4-6.4"/>


Because you are wrapping {{ entry.myCustomFieldValue }} in ', you are passing it as a string instead of its value, that's why you then see it as is in your result. Try:

{{ svg('@webroot/_dist/stat/link-arrow.svg')|attr({
    stroke: entry.myCustomFieldValue
}) }}
  • 1
    Also worth noting that you never nest twig tags, meaning never put {{ ... }} inside of another {{ ... }}; the same applies to {% ... %} as well (or any mixture of the two). Nov 23 '20 at 16:04
  • Perfect thanks Oli and good tip Jalen Davenport!
    – Martin
    Nov 23 '20 at 17:57

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.