Prevent template engine from parsing the content within the label

{% verbatim %}Tags are used forPrevent template engine from parsing the content within the label.

Main function

1. Protect JavaScript code

When JavaScript code contains characters that conflict with Django template syntax:

<script>
{% verbatim %}
    // 这里的 {{ }} 不会被 Django 解析
    var user = {{ name }};        // JavaScript 对象
    var message = "{{ text }}";   // JavaScript 字符串
{% endverbatim %}
</script>

2. Avoid syntax conflicts

Prevent Django from misinterpreting other template syntaxes (such as Vue.js, Angular, etc.):

<div id="app">
{% verbatim %}
    <!-- Vue.js 模板语法不会被 Django 处理 -->
    {{ message }}
    <div v-if="seen">现在你看到我了</div>
{% endverbatim %}
</div>

Example Usage

Do not use verbatim (has issues):

<script>
// Django 会尝试解析 {{ }},可能导致错误
var data = {{ json_data }};  // 如果 json_data 不存在会报错
</script>

Using verbatim (recommended):

<script>
{% verbatim %}
    // 安全地使用 {{ }} 语法
    var template = "{{ name }} - {{ age }}";
    var vueApp = new Vue({
        data: {
            message: 'Hello Vue!'
        }
    });
{% endverbatim %}
</script>

Precautions

  • verbatimAll template tags and variables within the block will not be processed
  • Commonly used for JavaScript framework integration
  • Maintain front-end template syntax coexistence with Django templates

This is a very useful tool when dealing with template syntax conflicts.