Search code examples
flaskjinja2

Make new multi line string variable in jinja template with other variables


I have some lenghty property tags I need to repeat on several attributes. For this example, let's assume it are some data-attributes, so

<tag1 data-attr1="{{value1}}" data-attr2="{{value2}}" ... data-attrN="{{valueN}}">
<tag2 data-attr1="{{value1}}" data-attr2="{{value2}}" ... data-attrN="{{valueN}}">
<tagX data-attr1="{{value1}}" data-attr2="{{value2}}" ... data-attrN="{{valueN}}">

I would like to rewrite this to not repeat the same string over and over. I'm trying the syntax below, but it results in an empty string.

{% set data_attributes = '
 data-attr1="{{value1}}" data-attr2="{{value2}}" 
 ... data-attrN="{{valueN}}"'%}
<tag1 {{data_attributes}}>
<tag2 {{data_attributes}}>
<tagX {{data_attributes}}>

Resulting HTML

 <tag 1 >
 <tag 2 >
 <tag 3 >

Solution

  • I had a long string and wanted to wrap it as well. This worked for me without issue.

    {% set error_message = 'Really long string that I wanted to wrap to 
                            multiple lines to help meet pep8 column width
                            error checking.' %}
    <p><strong>
      {{ error_message }}
    </strong></p>
    

    In your case though, I would probably do this instead.

      <div data-attr1="{{ variable_here }}"
           data-attr2="apples"
           data-attr3="oranges">
        Stuff
      </div>
    

    The rendered HTML would be:

    <div data-attr1="bananas" data-attr2="apples" data-attr3="oranges">
        Stuff
    </div>