You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:01:11