首页 > 解决方案 > Django将html代码从函数插入到模板中

问题描述

我从这篇文章中编辑了一个 python 函数,它创建了一个 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

这就是我在 html 文件中调用函数的方式:

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

这是我得到的纯文本的一部分

在此处输入图像描述

关于如何获取 html 代码之类的文本的任何想法?

标签: pythondjango

解决方案


实际上它返回一个字符串值,因此查找将删除字符串的属性或 js 函数


推荐阅读