简体   繁体   English

将python变量传递给javascript的Django模板Javascript

[英]Django template Javascript passing a python variable to a javascript one

I did create a python function called generate_random_number that generate a random number between 1 and 9 and compare it to the id of each video in my database and return the url of the video corresponding to the id matching the random number. 我确实创建了一个名为generate_random_numberpython函数,该函数generate_random_number 1到9之间的随机数,并将其与数据库中每个视频的id进行比较,然后返回与匹配该随机数的ID相对应的视频的url Here is the function: 这是函数:

from random import randint
from dash_interface.models import Video
from django import template

register = template.Library()


@register.simple_tag
def random_video():
    random_number = randint(1, 9)
    all_videos = Video.objects.all()
    for video in all_videos:
        if video.id == random_number:
           random_url = video.video_url
           return random_url

I want to pass random_url to a javascript variable in a django template. 我想将random_url传递给django模板中的javascript变量。

My template looks like this: 我的模板如下所示:

 <video id="videoplayer" controls></video> <script> {% load generate_random_number %} // setup the video element and attach it to the Dash player function setupVideo() { var url = " "; var context = new Dash.di.DashContext(); var player = new MediaPlayer(context); player.startup(); player.attachView(document.querySelector("#videoplayer")); player.attachSource(url); } </script> <style> video { width: 60%; height: 40%; } </style> 

The variable concerned is url . 有关的变量是url

I did a {% load generate_random_number %} , but I don't know if I can replace the quotation marks in url by {{ random_url }} . 我做了{% load generate_random_number %} ,但是我不知道是否可以用{{ random_url }}替换url的引号。

If you want to split the javascript code and html code, you could make something like: 如果要拆分javascript代码和html代码,可以执行以下操作:

<script arg = {{ somevar }} src = "/path/to/script"></script>

and in the script : 并在脚本中:

var arg = $("script[src='/path/to/script']").attr("arg");

If you need that the arg will be updated each a concrete period, you need to make an ajax. 如果需要在每个具体时间段内更新arg,则需要制作一个ajax。 If you use the database for persist the arg, you could use Django Channels like a more elegance solution. 如果使用数据库来持久化arg,则可以使用Django Channels作为更优雅的解决方案。

You should keep the custom template tag definitions in a templatetags folder inside your app. 您应该将自定义模板标签定义保存在应用程序内的templatetags文件夹中。 Make sure that __init__.py is present in the templatetags folder. 确保__init__.py存在于templatetags文件夹中。 Your folder structure should be similar to: 您的文件夹结构应类似于:

your_django_app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        template_tags.py
    views.py

And the contents of template_tags.py should be you required tag definition: 并且template_tags.py的内容应该是您所需的标记定义:

from random import randint
from dash_interface.models import Video
from django import template

register = template.Library()  

@register.simple_tag
def random_video():
    random_number = randint(1, 9)
    all_videos = Video.objects.all()
    for video in all_videos:
        if video.id == random_number:
           random_url = video.video_url
           return random_url

Note: The templatetags file should contain the variable named register . 注意: templatetags文件应包含名为register的变量。

After this you can load the template tags in your HTML. 之后,您可以在HTML中加载模板标签。 Your code will look like: 您的代码如下所示:

<video id="videoplayer" controls></video>
{% load template_tags %}

            <script>
            // setup the video element and attach it to the Dash player
            function setupVideo() {
              var url = "{% random_video %}";
              var context = new Dash.di.DashContext();
              var player = new MediaPlayer(context);
                              player.startup();
                              player.attachView(document.querySelector("#videoplayer"));
                              player.attachSource(url);
            }
            </script>

            <style>
            video {
              width: 60%;
              height: 40%;
            }
            </style>

This is the way I prefer to connect Django templates and JS. 这是我更喜欢连接Django模板和JS的方式。

You need to import render function: 您需要导入渲染功能:

views.py file views.py文件

from django.shortcuts import render
from random import randint
from dash_interface.models import Video

def random_video(request):
    random_number = randint(1, 9)
    all_videos = Video.objects.all()
    for video in all_videos:
        if video.id == random_number:
           random_url = video.video_url
           context = {
               "random_url": random_url
           }
           return render(request, "app/video.html", context)
        else:
           return render(request, "app/video.html", {})    

video.html video.html

<video id="videoplayer" controls></video>

            <script>
                {% load generate_random_number %}
            // setup the video element and attach it to the Dash player
            function setupVideo() {
              // using the context passed in here.
              var url = {{ random_url|safe }}; 
              var context = new Dash.di.DashContext();
              var player = new MediaPlayer(context);
              player.startup();
              player.attachView(document.querySelector("#videoplayer"));
              player.attachSource(url);
            }
        </script>

        <style>
        video {
          width: 60%;
          height: 40%;
        }
        </style>

What I have done is rendered your HTML page in the Django view and passed your variable inside the context dictionary which is later accessible in your HTML tags or script tags. 我所做的是在Django视图中呈现HTML页面,并将您的变量传递到上下文字典中,该字典以后可以在HTML标记或脚本标记中访问。

I also used a |safe parameter in the template tag which removes some unwanted strings. 我还在模板标记中使用了| safe参数,该参数除去了一些不需要的字符串。

Cheers and Hope it helps! 欢呼,希望对您有所帮助! I have tried this thing in many of my projects and it has always been a success for me. 我在许多项目中都尝试过此方法,对我而言一直是成功的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM