曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
0_Django开发常见问题

Solving Django and Vue.js Template Syntax Conflicts

Problem Django templates and Vue.js both wrap variables with {{ and }}. When rendering a Django template, all {{ and }} and the content wrapped in them are replaced first, so Vue.js cannot use {{ and }} to bind variables. Solutions Method 1: Change Vue.js's default binding delimiters Configure when creating the Vue App let app = new Vue({ delimiters: [[[, ]]], el: '#vu

曦远 (DealiAxy)约 5 分钟
目录6 个章节

Problem

Django templates and Vue.js both wrap variables with {{ and }}. When rendering a Django template, all {{ and }} and the content wrapped in them are replaced first, so Vue.js cannot use {{ and }} to bind variables.

Solutions

Method 1: Change Vue.js's default binding delimiters

Configure when creating the Vue App

let app = new Vue({
  delimiters: ["[[", "]]"],
  el: '#vue-app',
  // ...
})

Or change it globally

Vue.config.delimiters = ["[[", "]]"];

After doing this, you can use [[ and ]] to bind variable data

Method 2: Use template tags to output {{ and }}

Django's templatetag can output template tags when rendering the template. The tag arguments and their output are as follows:

ArgumentOutput
openblock{%
closeblock%}
openvariable{{
closevariable}}
openbrace{
closebrace}
opencomment{#
closecomment#}

We can use the following in the template

{% templatetag openvariable %} 
{% templatetag closevariable %}

to replace {{ and }}

Method 3: Disable Django template rendering

Django's verbatim tag keeps the code wrapped inside it from being rendered, outputting it as-is

{% verbatim %}
    {{ vue }}
{% endverbatim %}

We can wrap the parts needed for Vue.js with {% verbatim %}{% endverbatim %}.

finally

This project is a simple online exam system I made in 2020

In the end I used the first method

The code snippet is as follows

<div class="card-header d-flex justify-content-between">
  <div>
    第<b>[[currentShowIndex]]</b>题
    <span class="text-primary font-weight-bold" v-if="current.type==1">单选</span>
    <span class="text-primary font-weight-bold" v-if="current.type==2">多选</span>
    <span class="text-primary font-weight-bold" v-if="current.type==3">判断</span>
  </div>
  <div id="timer"></div>
</div>

_EOF_

Solving Django and Vue.js Template Syntax Conflicts

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…