[英]Django insert html code from function into template
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.我从这篇文章中编辑了一个 python function,这创建了一个 html 代码来显示文件夹中的图像并且它工作正常(我独立运行它并复制粘贴模板中的代码)但现在我想把它放在 Django 中所以我创建了一个模板标签,但我只得到纯文本。
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:这就是我在 html 文件中调用我的 function 的方式:
{% load static html_tags %}
{% generate_tree 'path' %}
and this is a portion of the plain text i get这是我得到的纯文本的一部分
any ideas on how can I get the text like html code?关于如何获取 html 代码之类的文本的任何想法?
make sure you use like this {{ text|safe }} in your template.确保在模板中使用这样的 {{ text|safe }} 。
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/ https://docs.djangoproject.com/en/4.1/ref/templates/builtins/
Actually it returns a string value so look up for a attribut or js function that will remove the strings实际上它返回一个字符串值,因此查找将删除字符串的属性或 js function
I found the answer in this post this post .我在这篇文章中找到了答案。 all i needed to do was to import
mark_safe
and use it the function我需要做的就是导入
mark_safe
并使用它 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.