0

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

我收到了这个错误

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>

表.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/'
  },
});

设置.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/',
            'STATS_FILE': os.path.join(BASE_DIR, 'staticfiles/bundles/stats.json')
        }
    })

CRISPY_TEMPLATE_PACK = 'bootstrap4'

# For Media

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

1 回答 1

0

table.html您使用标签render_bundle但尚未加载这些标签时(扩展一些加载这些标签的模板并不意味着该模板也可以使用它们)。在模板开头加载标签:

{% extends "base.html" %}
{% load render_bundle from webpack_loader %}

<!-- Rest of the template -->
{% render_bundle 'table' 'js' %}
<!-- Rest of the template -->
于 2021-03-29T14:56:15.200 回答