-1

I need to add some text in a HTML file, using Flask, with HTML tags enabled. If the HTML file looks like {{name}}, I can use flask like this:

@app.route('/')
def main():
    return render_template('template.html', name='name')

However, if I try the code below, the text between the <b> tag isn't bold.

@app.route('/')
def main():
    return render_template('template.html', name='<b>name</b>')

How can I change this?

1 Answers1

0

You could try using

{{ name | safe }}

Is there a reason you can't / don't want to do <b>{{ name }}</b>? Do you want different formatting depending on the name? In the case you could also use css and classes that depend on the name.

Max Leidl
  • 56
  • 3
  • The reason that I can't use `{{ name }}` is because the tags will be contained inside the name variable. EDIT: {{ name | safe }} worked. Thanks! I wonder what does the "|" do? – ApplesAndCode464 Aug 10 '22 at 09:40
  • Jinja (the templating engine flask uses) has something called [filters](https://jinja.palletsprojects.com/en/3.0.x/templates/#id11). The `|` is basically like calling any of the filters with the thing on the left side as its first argument. So what we are actually doing is calling `safe(name)` and the result is printed into the html. There is a bunch of [built in filters](https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-builtin-filters), which are enough for most use cases, but jinja also allows you to define your own :) – Max Leidl Aug 10 '22 at 10:19
  • 1
    Putting tags in variables is [often an antipattern](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/233676#233676). – ggorlen Aug 10 '22 at 15:04