[Django]-Django insert html code from function into template

3๐Ÿ‘

โœ…

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)
๐Ÿ‘คLuis Medina

1๐Ÿ‘

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

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

๐Ÿ‘คArchie

0๐Ÿ‘

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

๐Ÿ‘คFarhan Syedain

Leave a comment