Passing HTML to template using Flask/Jinja2

后端 未结 5 1417
灰色年华
灰色年华 2020-11-21 07:44

I\'m building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework

相关标签:
5条回答
  • 2020-11-21 07:56

    You can also declare it HTML safe from the code:

    from flask import Markup
    value = Markup('<strong>The HTML String</strong>')
    

    Then pass that value to the templates and they don't have to |safe it.

    0 讨论(0)
  • 2020-11-21 08:02

    From the jinja docs section HTML Escaping:

    When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

    Example:

     <div class="info">
       {{data.email_content|safe}}
     </div>
    
    0 讨论(0)
  • 2020-11-21 08:05

    Some people seem to turn autoescape off which carries security risks to manipulate the string display.

    If you only want to insert some linebreaks into a string and convert the linebreaks into <br />, then you could take a jinja macro like:

    {% macro linebreaks_for_string( the_string ) -%}
    {% if the_string %}
    {% for line in the_string.split('\n') %}
    <br />
    {{ line }}
    {% endfor %}
    {% else %}
    {{ the_string }}
    {% endif %}
    {%- endmacro %}
    

    and in your template just call this with

    {{ linebreaks_for_string( my_string_in_a_variable ) }}
    
    0 讨论(0)
  • 2020-11-21 08:12

    the ideal way is to

    {{ something|safe }}
    

    than completely turning off auto escaping.

    0 讨论(0)
  • 2020-11-21 08:22

    When you have a lot of variables that don't need escaping, you can use an autoescape block:

    {% autoescape off %}
    {{ something }}
    {{ something_else }}
    <b>{{ something_important }}</b>
    {% endautoescape %}
    
    0 讨论(0)
提交回复
热议问题