454
If you donβt want the HTML to be escaped, look at the safe
filter and the autoescape
tag:
safe
:
{{ myhtml |safe }}
{% autoescape off %}
{{ myhtml }}
{% endautoescape %}
42
If you want to do something more complicated with your text you could create your own filter and do some magic before returning the html.
With a templatag file looking like this:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def do_something(title, content):
something = '<h1>%s</h1><p>%s</p>' % (title, content)
return mark_safe(something)
Then you could add this in your template file
<body>
...
{{ title|do_something:content }}
...
</body>
And this would give you a nice outcome.
- [Django]-Django datetime issues (default=datetime.now())
- [Django]-Django.contrib.auth.logout in Django
- [Django]-How to submit form without refreshing page using Django, Ajax, jQuery?
40
You can render a template in your code like so:
from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')
c = Context({'message': 'Your message'})
html = t.render(c)
See the Django docs for further information.
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-Django: Implementing a Form within a generic DetailView
- [Django]-Django index page best/most common practice
38
Use the autoescape
to turn HTML escaping off:
{% autoescape off %}{{ message }}{% endautoescape %}
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-Resource temporarily unavailable using uwsgi + nginx
- [Django]-Using the reserved word "class" as field name in Django and Django REST Framework
18
The simplest way is to use the safe
filter:
{{ message|safe }}
Check out the Django documentation for the safe filter for more information.
- [Django]-Django β Annotate multiple fields from a Subquery
- [Django]-Choose test database?
- [Django]-How do I POST with jQuery/Ajax in Django?
13
No need to use the filter or tag in template.
Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.
format_html("<h1>Hello</h1>")
Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html
- [Django]-How to put comments in Django templates?
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django character set with MySQL weirdness
- [Django]-Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-How to resize the new uploaded images using PIL before saving?