简体   繁体   English

Django 在 javascript 中的模板标签

[英]Django's template tag inside javascript

My app's urls.py is:我的应用程序的 urls.py 是:

from django.urls import path
from . import views

app_name = 'javascript'
urlpatterns = [
    path('create_table', views.create_table, name='create_table')

My views.py is:我的 views.py 是:

def create_table(request):
    row_data = "this is row data"
    context = {'row_data': row_data}
    return render(request, 'javascript/create_table.html', context)

My create_table.html is:我的 create_table.html 是:

{% load static %}
<button id="create_table">Get data</button>
<div id="place_for_table"></div></div>
<script src="{% static 'javascript/scripts/create_table.js' %}"></script>

And my create_table.js is:我的 create_table.js 是:

function create_table() {
    document.getElementById("place_for_table").innerHTML = '{{ row_data }}';
}

document.getElementById("create_table").onclick = function() {
    create_table()
}

What I am trying to do is to run the create_table.js script on the click of the create_table button which should display "this is row data" text in place for table div element.我想要做的是在单击create_table按钮时运行 create_table.js 脚本,该按钮应place for table div 元素显示“这是行数据”文本。

However, what gets diplayed is just {{ row_data )) .但是,显示的只是{{ row_data ))

I have read other similar questions on using Django's variables inside Javascript but as per my understanding they all suggest to do the way I did it, so I am not sure what I am doing wrong.我已经阅读了其他关于在 Javascript 中使用 Django 变量的类似问题,但根据我的理解,他们都建议按照我的方式去做,所以我不确定我做错了什么。

If you've got an element in your template which you're getting to then detect clicks, why not just do it the other way around where you can then pass the context variable to your JS function?如果您的模板中有一个要检测点击的元素,为什么不换一种方式将上下文变量传递给您的 JS 函数呢?

<button onclick="create_table({{ row_data }})">Click me</button>

By doing that you can inspect the page to see if the data is going to be passed correctly.通过这样做,您可以检查页面以查看数据是否将被正确传递。 You'll probably have to pass the data through a filter like escapejs or safe .您可能必须通过像escapejssafe这样的过滤器传递数据。

Alternatively you could do something like或者你可以做类似的事情

{% load static %}

<button id="create_table">Get data</button>
<div id="place_for_table"></div></div>

<script type="text/javascript">
    var row_data = "{{ row_data }}";
</script>
<script src="{% static 'javascript/scripts/create_table.js' %}">
</script>

The issue with this approach is the scope of variables as you may not want to declare things globally so it could be considered an easy approach, but not necessarily the best solution.这种方法的问题是变量的范围,因为您可能不想全局声明事物,因此它可以被认为是一种简单的方法,但不一定是最佳解决方案。

When you write {{ row_data }} , you're using a Django-specific "language" called Django template language which means that the mentioned syntax can only be "understood" by Django templates.当您编写{{ row_data }}时,您使用的是 Django 特定的“语言”,称为Django 模板语言,这意味着上述语法只能被 Django 模板“理解”。

What you're doing here is loading a separate JavaScript file in which the Django template syntax simply won't work because when browser comes to the point to evaluate that file, {{ row_data }} will look just another string literal, and not what you would expect to.你在这里做的是加载一个单独的 JavaScript 文件,Django 模板语法在其中根本不起作用,因为当浏览器到达评估该文件的位置时, {{ row_data }}看起来只是另一个字符串文字,而不是什么你会期望。

It should work if you inline your JavaScript example directly into the Django template.如果您将 JavaScript 示例直接内联到 Django 模板中,它应该可以工作。

Alternatively you could somehow "bootstrap" the external JavaScript file with the data available in the Django template, here's how I would go about doing that:或者,您可以使用 Django 模板中可用的数据以某种方式“引导”外部 JavaScript 文件,以下是我将如何去做:

create_table.html创建_table.html

<script src="{% static 'javascript/scripts/create_table.js' %}"></script>
<script type="text/javascript">
$(function() {
  var create_table = Object.create(create_table_module);
  create_table.init({
    row_data: '{{ row_data }}',
    ...
  });
});
</script>

Note: wrapping the above code in the jQuery's .ready() function is optional, but if you're already using jQuery in your app, it's a simple way to make sure the DOM is safe to manipulate after the initial page load.注意:将上述代码包装在 jQuery 的.ready()函数中是可选的,但如果您已经在您的应用程序中使用 jQuery,这是确保 DOM 在初始页面加载后可以安全操作的简单方法。

create_table.js创建表.js

var create_table_module = (function($) {
  var Module = {
    init: function(opts) {
      // you have access to the object passed
      // to the `init` function from Django template
      console.log(opts.row_data)
    },
  };

  return Module;
})(jQuery);

Note: passing jQuery instance to the module is optional, it's just here as an example to show how you can pass an external dependancy to the module.注意:将 jQuery 实例传递给模块是可选的,它只是在这里作为一个示例来展示如何将外部依赖项传递给模块。

What I did was to include the javascript/jquery inside {% block scripts %} and use the the Django specific data as follows:我所做的是在 {% block scripts %} 中包含 javascript/jquery 并使用 Django 特定数据,如下所示:

$.ajax({ type:"GET", url: "/reserve/run/?ip={{ row_data }}", dataType: "html", async: true, }).done(function(response) { $("#Progress").hide(); $('#clickid').attr('href','javascript:ClearFlag()'); var win = window.open("", "MsgWindow"); win.document.write(response); });

I've found a solution to avoid the extra typing of all the previous answers.我找到了一种解决方案,可以避免对之前的所有答案进行额外输入。

It's a bit hacky:这有点老套:

Just transform you myjavascriptfile.js into myjavascriptfile.js.html and wrap the code in a <script>...</script> tag.只需将myjavascriptfile.js转换为myjavascriptfile.js.html并将代码包装在<script>...</script>标记中。 Than include them instead of linking them in your template file.include它们而不是将它们链接到模板文件中。

myTemplate.html我的模板.html

    ....
    {% block js_footer %}
    {% include "my_app/myjavascriptfile.js.html" %}
    {% endblock js_footer %}

myjavascriptfile.js.html我的javascriptfile.js.html

<script type="text/javascript">
    console.log('the time now is {% now "Y m d H:i:s" %}');
    ...
</script>

instead of writing the function in a separated js file, write it in script tags within your html page, so it can use the django template language不要将函数写在单独的 js 文件中,而是将其写在 html 页面中的脚本标签中,这样它就可以使用 django 模板语言

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

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