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

如何在Django模板的JavaScript代码中原样嵌入Python列表?

解决Django模板中将Python列表嵌入JavaScript的问题

看起来你想把视图里传入的Python列表直接作为Dygraph的labels参数,直接用{{ biogas_plant_list }}可能会出问题——因为Django默认会把Python列表渲染成类似['label1', 'label2']的字符串,不仅会带多余的引号,而且如果列表里有特殊字符还会被转义,甚至Python的布尔值(True/False)和JS的(true/false)格式不兼容。

下面给你两种靠谱的解决方案:

方法1:使用Django内置的json_script标签(推荐)

这是Django官方推荐的安全传递Python数据到JS的方式,它会自动处理转义和格式问题:

  1. 首先在模板的任意位置(比如footer_javascript_section块外面)添加:
{{ biogas_plant_list|json_script:"biogas-labels" }}

这会生成一个type为application/json的script标签,id是biogas-labels,内容是序列化后的JSON数组。

  1. 然后修改你的JS代码,读取这个JSON内容:
{% block footer_javascript_section %}
<script type="text/javascript" >
  // 读取序列化后的JSON数组
  const labels = JSON.parse(document.getElementById('biogas-labels').textContent);
  g = new Dygraph(
    // 容器div
    document.getElementById("graphdiv"),
    // CSV文件或其路径
    "{{ biogas_plant_str }}",
    {
      width: 1000,
      height: 400,
      labels: labels /* <---- 这里用读取到的数组 */
    }
  );
</script>
{% endblock footer_javascript_section %}

方法2:在视图中序列化后传递到模板

如果你更习惯在后端处理,可以用json.dumps把列表转成JS兼容的JSON字符串:

  1. 在视图函数里导入json,并处理上下文:
import json

def your_chart_view(request):
    # 假设你的Python列表是这个
    biogas_plant_list = ["日期", "产气量", "温度"]
    context = {
        "biogas_plant_str": "your_csv_path_or_data",
        # 把列表转成JSON字符串
        "biogas_plant_list_json": json.dumps(biogas_plant_list)
    }
    return render(request, "chart.html", context)
  1. 然后在模板里用safe过滤器直接输出(因为JSON字符串本身就是合法的JS数组格式):
{% block footer_javascript_section %}
<script type="text/javascript" >
  g = new Dygraph(
    // 容器div
    document.getElementById("graphdiv"),
    // CSV文件或其路径
    "{{ biogas_plant_str }}",
    {
      width: 1000,
      height: 400,
      labels: {{ biogas_plant_list_json|safe }} /* <---- 直接使用序列化后的JSON */
    }
  );
</script>
{% endblock footer_javascript_section %}

注意事项

  • 不要直接使用{{ biogas_plant_list|safe }},因为Python列表的字符串表示(比如['a', 'b'])和JS数组的语法虽然相似,但存在细节差异(比如Python的True会被渲染成True,而JS需要true),会导致JS报错。
  • json_script标签会自动处理XSS风险,是更安全的选择,尤其当列表内容来自用户输入时。

内容的提问来源于stack exchange,提问作者devsaw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:58:59