javascript - 如何在没有 Node 的情况下在 .pug 文件和链接的 .js 文件之间交换数据?
问题描述
是否可以在不使用 Node的情况下将数据从.js
文件传递到文件?.pug
我正在使用一个非常基本的设置来运行我的项目并将其与 Parcel.js 捆绑在一起。我没有使用带有 Express 的 Node.js 后端,我也不渴望这样做。我只是希望能够在我的app.js
-file 中获取数据并使用 Pug 显示它。但即使这个设置也没有name
在页面上显示 - 变量:
指数.pug
doctype html
html(lang="en")
head
title Homepage
body
p My name is #{name}
script(type="module", src="./app.js")
应用程序.js
const name = "Holy Kiwi";
包.json
{
"name": "frontend-javascript-edhub-pug",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "parcel index.pug",
"build": "parcel build index.pug"
},
"devDependencies": {
"@parcel/transformer-pug": "^2.0.0",
"parcel": "^2.0.0",
},
"dependencies": {
"pug": "^3.0.2"
}
}
我尝试过的其他没有用的东西
- 从
app.js
脚本中导出变量:export const name = 'Kiwi';
; - 创建一个 pug 变量,然后将脚本变量导入其中:
- const name = import { name } from './app.js';
我真的希望你能帮助我!
解决方案
当您安装了pug
软件包后,您可以使用以下renderFile
方法:
const pug = require("pug");
const html = pug.renderFile("./path_to/index.pug", { name: "Holy Kiwi"});
上面在 object 中产生了以下字符串html
,你可以根据自己的需要“显示”它:
<!DOCTYPE html><html lang="en"><head><title>Homepage</title></head><body><p>My name is Holy Kiwi</p><script type="module" src="./app.js"></script></body></html>
推荐阅读
- excel - 包括 SUB 而 .SAVEAS
- matlab - 预测 SVM 回归的测试样本响应
- python - python清理文本数据
- node.js - 当用户从数据库中删除时删除帖子
- bots - 有一个角色来反应 discord.js
- azure - Azure Function 未将 LogMetric 遥测记录到 Application Insights
- python - 告诉 bazel 将 .so 文件复制到 py_library 输出文件夹中?
- r - 在另一个数据框中搜索一列名称,并结合其他列的数据获取结果
- ruby-on-rails - ElasticSearch maxClauseCount 设置为 1024
- javascript - 按下按钮时内容未加载