Django 模板语法错误 - Django Webpack

问题描述

我正在开发 django webpack 包。我在 github 上有一个现成的模板。我对其进行了一些更改。我根据自己的文件层次结构准备将来使用。但是我在模板语法方面遇到了问题。首先,我的项目中有 base.html。感谢这个页面,形成了我以后要创建的页面的背景。一些文件是在 base.html 中导入的。这些是使用 render_bundle 和静态标签实现的。我创建了一个要在 Django 中呈现的新页面。同样,我想在此页面上与其他页面分开导入 assets/js/table.js 和 assets/scss/table.scss 文件。但我收到模板语法错误。你觉得我哪里做错了?

i got this error

base.html

{% load render_bundle from webpack_loader %}
{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
    <Meta charset="UTF-8">
    {% block Meta %}
      
    {% endblock Meta %}
    <title>
        {% block title %}
        
        {% endblock %}
    </title>

    <!-- You should added this tags for production files !!! -->
    {% render_bundle 'app' 'css' %}
    {% render_bundle 'myapp' 'css' %}
    <link href="/media/favicon.png" rel=icon>

    {% block head %}

    {% endblock %}
</head>

<body>
    {% include "navbar.html" %}
    
    <!-- Content -->
    {% block body %}

    {% endblock %}

    <!-- Start -->
    {% if settings.DEBUG and settings.WEBPACK_LIVE_SERVER %}
    <!-- You should added this tags for development files -->
    <script src="{{ settings.WEBPACK_LIVE_SERVER_CONfig.ADDRESS }}/vendor.bundle.js"></script>
    <script src="{{ settings.WEBPACK_LIVE_SERVER_CONfig.ADDRESS }}/app.bundle.js"></script>
    <script src="{{ settings.WEBPACK_LIVE_SERVER_CONfig.ADDRESS }}/myapp.bundle.js"></script>
    {% else %}
    <!-- You should added this tags for production files !!! -->
    {% render_bundle 'vendor' 'js' %}
    {% render_bundle 'app' 'js' %}
    {% render_bundle 'myapp' 'js' %}
    {% endif %}
    <!-- End -->

    {% block scriptblock %}
      
    {% endblock scriptblock %}

    <!-- Your static import javascript modules -->
    <script src="{% static 'new.js' %}"></script>
</body>

</html>

table.html

{% extends "base.html" %}

{% block title %}
Table Test Page
{% endblock title %}

{% block head %}

{% render_bundle 'table' 'css' %}

{% endblock head %}

{% block body %}

<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsa,sed.</p>

{% endblock body %}

<!-- Start -->
<!-- Import JS Files for Development and Production -->
{% if settings.DEBUG and settings.WEBPACK_LIVE_SERVER %}
<script src="{{ settings.WEBPACK_LIVE_SERVER_CONfig.ADDRESS }}/table.bundle.js"></script>
{% else %}
<!-- You should added this tags for production files !!! -->
{% render_bundle 'table' 'js' %}
{% endif %}
<!-- End -->

webpack.common.js

const path = require('path')

var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    app: "./assets/js/app.js",vendor: "./assets/js/vendor.js",myapp: "./assets/js/myapp.js",table: "./assets/js/table.js",},module: {
    rules: [{
        test: /\.html$/,use: ["html-loader"]
      },{
        test: /\.(svg|png|jpg|gif)$/,use: {
          loader: "file-loader",options: {
            name: "[name].[hash].[ext]",outputPath: "imgs"
          }
        }
      }
    ]
  }
};

webpack.dev.js

const path = require("path");
const common = require("./webpack.common");
const { merge } = require("webpack-merge");
const { CleanWebpackPlugin }= require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const BundleTracker = require('webpack-bundle-tracker');

module.exports = merge(common,{
  mode: "development",output: {
    filename: "[name].bundle.js",path: path.resolve(__dirname,"./assets/bundles/dev"),publicPath: "/static/dev/",plugins: [
    new MiniCssExtractPlugin({ filename: "[name].bundle.css" }),new CleanWebpackPlugin(),new BundleTracker({path: __dirname,filename: './assets/bundles/dev/stats.json'})
  ],module: {
    rules: [
      {
        test: /\.scss$/,use: [
          "style-loader",//3. Inject styles into DOM
          "css-loader",//2. Turns css into commonjs
          "sass-loader" //1. Turns sass into css
        ]
      }
    ]
  },devServer: {
    hot: true,compress: true,publicPath: '/static/dev/'
  },});

settings.py

"""
Django settings for app project.

Generated by 'django-admin startproject' using Django 2.2.4.

For more information on this file,see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values,see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR,...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# Security WARNING: keep the secret key used in production secret!
SECRET_KEY = ')u)=q2gh%++e1!h(q5*+sa^nn8ygszg=dqfr7a!0ogzleh=i6k'

# Security WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application deFinition

INSTALLED_APPS = [
    'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',# Third party apps
    'webpack_loader','crispy_forms','django_extensions'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]

ROOT_URLconf = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates','Dirs': [os.path.join(BASE_DIR,'templates')],'APP_Dirs': True,'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],]

Wsgi_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3','NAME': os.path.join(BASE_DIR,'db.sqlite3'),}
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',{
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',{
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',{
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

STATICFILES_Dirs = [
    os.path.join(BASE_DIR,'assets/staticfiles'),os.path.join(BASE_DIR,'static/'),]

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/dev/','POLL_INTERVAL': 0.1,'TIMEOUT': None,'STATS_FILE': os.path.join(BASE_DIR,'assets/bundles/dev/stats.json')
    }
}

# Live reload server setting
WEBPACK_LIVE_SERVER = True

if DEBUG and WEBPACK_LIVE_SERVER:
    WEBPACK_LIVE_SERVER_CONfig = {
        'ADDRESS': 'http://localhost:8080/static/dev'
    }

if not DEBUG:
    WEBPACK_LOADER.update({
        'DEFAULT': {
            # 'BUNDLE_DIR_NAME': 'bundles/','staticfiles/bundles/stats.json')
        }
    })

CRISPY_TEMPLATE_PACK = 'bootstrap4'

# For Media

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR,"media/")

解决方法

POST 中,您使用了标签 table.html,但您还没有加载这些标签(扩展一些加载这些标签的模板并不意味着该模板也可以使用它们)。在模板开头加载标签:

render_bundle