tags:

views:

56

answers:

3

I have to send make some text bold in between plain text and send it to the template from the view. I do this:

I save a string like this <b>TextPlaintext</b> in a variable and return it to the template. The "<b>" tags are not interpreted.

How can make some text bold in a django view?

+5  A: 

Django automatically escapes string values in templates, to improve security.

If you know that a value has HTML in it, and is trusted, then you can turn off escaping:

{{my_trusted_html|safe}}
Ned Batchelder
+1 for being *correct*, but the OP is making a more fundamental mistake in doing any kind of text formatting in the view, as @Sébastien Piquemal points out.
Gabriel Hurley
I'm not so dogmatic as you, I guess. There are reasons for creating HTML content in a view, or even in a model, or stored in a database. Knowing how to get that data onto the page correctly is a useful tool. I don't presume to know enough about the OP's problem to say whether he is doing something as bad as "making a mistake".
Ned Batchelder
+1  A: 

You can use the autoescape tag in a django template.

Also, if you write your own filter, you can control whether or not it is escaped.

BernzSed
+2  A: 

Making a text bold shouldn't be done in the view. Indeed, the view should not take care of formatting (which is the role of templates). What you can do however, is adding an extra variable to the rendering context, and depending on its value, make the text bold or not in the template.

For example :

In the view :

#...
is_important = True if something else False
extra_context.update({'is_important': is_important})
#...

In the template :

...
{% if is_important %}<bold>{{ text_to_render }}</bold>{% else %}{{ text_to_render }}{% endif %}
...

But more generally, deciding if a text is bold or not, is not even formatting, rather styling and should not be made in the template (so you shouldn't use the <bold> markup). So I would suggest :

...
<span {% if is_important %}class="is-important"{% endif %}>
{{ text_to_render }}
</span>
...

And a stylesheet :

.is-important{
    font-weight: bold;
}
sebpiq