python - 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 代码之类的文本的任何想法?
解决方案
实际上它返回一个字符串值,因此查找将删除字符串的属性或 js 函数
推荐阅读
- react-native - 第三方包中的 pod 文件是否必须在 react-native 项目中使用新的 react-native 版本
- c# - Web API / MVC 的 VS 解决方案配置
- python - 绘图:具有三列的堆栈栏
- mongodb - elemMatch 用于不同级别的字段
- c# - 是否有任何 js 雷达图表库可以在控制台应用程序上与 Tuesspechkin 一起使用?
- python - 在函数中计算并在另一个函数中调用
- arrays - 在 Rails 中验证数组插入
- modbus-tcp - 如何使用 Modbus TCP/IP 从 FLIR AX8 相机获取温度值
- node.js - 部署到 AWS lambda 后,用于 Node.js 的 Nexmo 客户端库正在运行
- r - 使用 lapply 使对象名称成为数据框中的新列