【问题标题】:pass django template file content to javascript将 django 模板文件内容传递给 javascript
【发布时间】:2021-10-29 11:32:30
【问题描述】:

我想将模板文件内容传递给我的 javascript 文件,以供以后在其中创建 DOM 元素。 我所尝试的是将它作为带有如下包含标记的变量传递给 js:

<script>const list_item = {% include 'myapp/list_item.html' %}</script>

但这最终得到:

Uncaught SyntaxError: Unexpected token '

有没有办法可以将模板文件内容传递给 js 文件?

提前致谢

【问题讨论】:

    标签: javascript django django-templates


    【解决方案1】:

    仅查看您的样本(不对实现预期结果的其他可能方法提出任何建议),它应该是:

    <script>const list_item = "{% include 'myapp/list_item.html' %}";</script>
    

    模板文件的内容应该作为字符串包含,否则会一直抛出语法错误。

    【讨论】:

    • 谢谢!它解决了我必须使用 ` 而不是 " 以避免与模板双引号冲突的问题。
    猜你喜欢
    • 2018-08-30
    • 2018-12-03
    • 2015-11-23
    • 2023-02-25
    • 2018-08-24
    • 2018-04-13
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多