PUG中的绝对路径 [英] Absolute path in PUG
问题描述
根据 PUG 文档( https://pugjs.org/language/includes.html ):
如果路径是绝对路径(例如,包含/root.pug),则通过以下方式解析 在options.basedir之前.否则,路径将相对于 当前正在编译的文件.
If the path is absolute (e.g., include /root.pug), it is resolved by prepending options.basedir. Otherwise, paths are resolved relative to the current file being compiled.
我了解其中包括将路径介词作为选项传递给res.render(). 但是,我想避免尽可能多地重复自己的麻烦,并且希望使用顶级解决方案.
Which I understand consists of passing the path preposition as an option to res.render(). However, I want to avoid the trouble of repeating myself as much as I can and would prefer a top-level solution.
我尝试使用app.locals.basedir
,但是我的代码无法使用basedir
路径.因此,找不到该文件.
I tried using app.locals.basedir
but my code fails to preprend the basedir
path. The file therefore cannot be found.
这是我的 Express.js 应用程序索引的中坚力量:
Here is the backbone of my Express.js app index:
// index.js
const express = require('express');
const app = express();
const path = require('path');
app.locals.basedir = __dirname;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.get('/', function(req, res){
res.render('index');
});
app.listen(3000, function(){
console.log('Server started on port 3000');
});
我的 PUG 文件如下:
// views/index.pug
doctype html
html
head
script(type='text/javascript' src='/public/lib/map.js' defer='defer')
title ExpressApp
body
h1 Hello, World!
我的项目结构:
project/
index.js
views/
index.pug
public/
lib/
map.js
在 PUG 文件中使用绝对路径插入javascript文件的正确方法是什么?
What is the correct way of inserting a javascript file using an absolute path in a PUG file?
推荐答案
在 Express.js 应用中,只需使用app.use(express.static('public'))
设置Web根目录,以便应用程序知道在哪里提取静态文件.
不需要app.locals.basedir = __dirname
.
In the Express.js app, the web root simply needs to be set using app.use(express.static('public'))
so that the application knows where to fetch the static files.
app.locals.basedir = __dirname
is not needed.
因此在 PUG 文件中,应按以下方式插入脚本:
In the PUG file, the script should therefore be inserted as follows:
script(type='text/javascript' src='/lib/map.js' defer='defer')
这篇关于PUG中的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!