python - 使用 Django 在 HTML 上动态变量值

标签 python html django dynamic tags

我希望将一个不断变化的 python 变量(从 websocket 服务器读取)显示到 HTML 文件上,目前我正在使用 Django 标签,如下所示:

templatetags/mytag.py

from django import template
register = template.Library()
current_value = 0

@register.filter
def c_value(placeholder):
    return current_value

#more code that modifies current_value reading from a websocket server

index.html

{% load mytag %}
<script>
function mytimer() {
  setInterval(function(){ 
                $('#stuff').html( {{ placeholder|c_value }} ); 
              }
              , 1000);
}
mytimer();
</script>

#some code from the website

<span id="stuff">Holder</span>

然而,“{{ placeholder|c_value }}”自然只会输出“current_value”的第一个值,在本例中为 0,因此 index.html 的源代码最终为:

“{{ placeholder|c_value }}”之后的源代码

<script>
function mytimer() {
  setInterval(function(){ 
                $('#stuff').html( 0 ); 
              }
              , 1000);
}
mytimer();
</script>

这不是我们想要的,因为我们希望每秒打印“current_value”的变化值。

处理这类动态文本的正常方法是什么?非常感谢!

最佳答案

要实现此行为,您需要执行一些操作。

  1. 设置一个返回您感兴趣的值的网址。例如,设置您的网站,以便网址 http://example.com/c_value 返回响应并提供正确的信息。以 JSON 格式返回响应通常是个好主意;在 Django 中,您可以使用 JsonResponse 类来执行此操作。假设您返回文本:

    {
        "c_value": "foo"
    }
    
  2. 更改您的页面,以便不再从模板加载变量,而是向您设置的地址发出请求。如果您使用 jQuery,则可以使用 $.ajax函数来执行此操作(或 $.getJSON ,它只是 $.ajax 的简写函数,仅包含 JSON 数据)。假设返回的 JSON 与我在步骤 1 中给出的示例匹配,您的计时器内可能会出现类似的情况。(data 将包含您从服务器发送的 JSON 对象) .

    $.ajax({
        dataType: "json",
        url: "http://example.com/c_value",
        success: function(data) {
            $('#stuff').html(data["c_value"]);
        }
    });
    

关于python - 使用 Django 在 HTML 上动态变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49143227/

相关文章:

python - 基于已知相机方向的 OpenCV 中的透视变形

python - 如何使用转换器插件将 shapefile 转换为 jvectormap?

python - 对平面内容执行文本处理以包括自定义标记的处理

html - <base href> 和搜索引擎

html - 一维不变的 CSS 三 Angular 形

javascript - 如何使用 JavaScript 禁用/启用 HTML5 视频标签

python - Python 中的数据格式化和操作

python - 如何将 Django 作为服务运行?

python - 如何测试 django 缓存?

python - 反转 'update_comment',参数为 '(' ',)' not found. 1 pattern(s) tried: [' comment\\/(?P<news_pk>[0-9]+)$']