如何在Django的static模板标签中嵌入对象变量?
Django static模板标签中使用对象变量的正确写法
你原来的写法问题在于Django模板标签内部无法嵌套{{}}变量语法,解析器不会处理{% static %}标签里的{{obj.id}},所以需要用模板过滤器或提前定义变量来拼接路径,以下是几种可行方案:
直接用
add过滤器拼接字符串:<script src="{% static 'base/js/'|add:obj.id|add:'_container.js' %}"></script>先通过
with标签定义完整路径,再传入static:{% with js_file_path='base/js/'|add:obj.id|add:'_container.js' %} <script src="{% static js_file_path %}"></script> {% endwith %}若使用Django 2.1及以上版本,可利用
format过滤器简化拼接:<script src="{% static 'base/js/{0}_container.js'|format:obj.id %}"></script>
内容的提问来源于stack exchange,提问作者Mathew O'Sullivan
相关产品推荐
相关产品推荐

