【问题标题】:Django : combine variable and HTML id in templateDjango:在模板中组合变量和 HTML id
【发布时间】:2017-04-03 00:39:05
【问题描述】:

我正在寻找一种使用 Javascript 变量“连接”django 对象列表(通过views.py 中的get_queryset 获取)的方法。然后将它们连接到模型对象的字段。

我的模型是一篇博文,包含 post_title 字段(一个字符字段)。 在我的 index.html 中,我有一个 id="1" 或 id="2" 对应于页面索引和 onClick="displayPostContentOnPageButtonCliked(this.id)" 属性的寻呼机按钮。

我的 index.html 检索名为 all_post_by_date 的 context_object_name 中的所有帖子对象。 在我的 index.html 中,我想在警报对话框中显示与单击的按钮相对应的帖子标题,例如:

<script>
    function displayPostContentOnPageButtonCliked(page_button_clicked_id){
        var all_posts_by_date = "{{all_posts_by_date.page_button_clicked_id.post_title}}";
        alert(all_posts_by_date);
    }
</script>

但这不起作用。我尝试添加过滤器或创建自己的过滤器(称为 get_index,但只能设法获得:all_posts_by_date|get_index:page_button_clicked_id 并且无法组合 .post_title 部分。 我的问题是:如何让 {{all_posts_by_date.page_button_clicked_id.post_title}} 工作,并在单击按钮 3 时提醒“帖子 3 的标题”? 谢谢你!

【问题讨论】:

  • 请发布您的完整模板。

标签: javascript python html django templates


【解决方案1】:

为您提供两种解决方案:(1)在对 JS 函数的调用中将您想要的数据发送到您的 JS 函数。

<script>
    function showPostTitle(post_title){
        alert(post_title);
    }
</script>

. . .
{% for x in all_posts_by_date %}
<div id='blog-post-{{ x.id }}' on-click="showPostTitle('{{ x.post_title }}')">
. . . 
{% endfor %}

或者你可以自己序列化数据以备后用:

<script>
    var titles = [];
{% for x in all_posts_by_date %}
    titles.push('{{ x.post_title }}');
{% endfor %}
    function displayPostContentOnPageButtonCliked(nId) {
        var title = titles[nId - 1];
        alert(title);
    }
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多