Django insert html code from function into template

Question:

I have a python function edited from this post, this creates an html code to display the images in a folder and it works fine ( I run it independently and copy paste the code in the template ) but now I want to make it inside Django so I create a templatetag but I only get plain text.

from django import template
import os 
from pathlib import Path

register = template.Library() 

@register.simple_tag
def generate_tree():
    for file in os.listdir(path):
        rel = path + "/" + file
        if os.path.isdir(rel):
            html += """<button type="button" class="collapsible">%s</button>"""% (file)
            html +='<div class="content">'
            html += generate_tree(rel)
            html += '</div>'
        else:
            html +='<div class="col-md-4 d-flex align-items-stretch"> <picture>'
            x=str(rel)[38:]
            html += """<img src="{% static "%s" """% ('% s',x)
            html += """%} " class="lazy card-img-top" >"""
            html +='</picture> </div>'
    return html

this is how i call my function in the html file:

{% load static html_tags %}
{% generate_tree 'path' %}

and this is a portion of the plain text i get

enter image description here

any ideas on how can I get the text like html code?

Asked By: Luis Medina

||

Answers:

Actually it returns a string value so look up for a attribut or js function that will remove the strings

Answered By: Farhan Syedain

I found the answer in this post this post. all i needed to do was to import mark_safe and use it the function

from django.utils.safestring import mark_safe
from django import template
import os 
from pathlib import Path

register = template.Library() 

@register.simple_tag
def generate_tree():
    for file in os.listdir(path):
        rel = path + "/" + file
        if os.path.isdir(rel):
            html += """<button type="button" class="collapsible">%s</button>"""% (file)
            html +='<div class="content">'
            html += generate_tree(rel)
            html += '</div>'
        else:
            html +='<div class="col-md-4 d-flex align-items-stretch"> <picture>'
            x=str(rel)[38:]
            html += """<img src="{% static "%s" """% ('% s',x)
            html += """%} " class="lazy card-img-top" >"""
            html +='</picture> </div>'
    return mark_safe(html)
Answered By: Luis Medina

make sure you use like this {{ text|safe }} in your template.

https://docs.djangoproject.com/en/4.1/ref/templates/builtins/

Answered By: Archie
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.