Home > Software engineering >  How to set a html attribute value via ternary?
How to set a html attribute value via ternary?

Time:05-08

I've tried countless options, but I never get the quotes to wrap around the entire value as soon as there's a space within the value string:

{% set result_string= elements
        ? ( "data-custom-attribute=%s"|format( elements ) )
        : ''
%}

How can you make this work to get for example data-custom-attribute="this is a test" with elements having the value 'this is a test' ?

CodePudding user response:

The filter format will not add any quotes to the example you've added in your snippet.

You are probably verifying your output in some developer tools which give a false-positive. Verify your output with the generated source (CTRL U)

Either add the quotes in the variable elements or add them in your html snippet:

{% set elements = "\"foo bar foo\"" %}
{% set result_string= elements
        ? ( "data-custom-attribute=%s"|format( elements ) )
        : ''
%}

{% set elements = "foo bar foo" %}
{% set result_string= elements
        ? ( "data-custom-attribute=\"%s\""|format( elements ) )
        : ''
%}

demo

  • Related