簡體   English   中英

最簡單的 node.js + nunjucks 示例

[英]Simplest possible node.js + nunjucks example

可能永遠不會使用 node.js 或 Nunjucks 進行任何實際開發,但現在出於某種原因需要:

  • 使用 Nunjucks 將一些簡單的模板預編譯為Nunjucks
  • node.js下運行預編譯模板

我已經做好了:

  • 安裝了node.jsnpm (例如有nodenpm命令)
  • mkdir njtest && cd njtest
  • 使用npm install nunjucks (獲得了node_modules/nunjucks目錄)
  • mkdir templates
  • 在模板中,我創建了兩個文件index.htmllayout.html ,其中包含以下jinja2/nunjucks內容

  • layout.html

<!doctype html>
<head>
        <title>simple example</title>
</head>
<body>
        <h1>Simple example</h1>
        {% block body %}{% endblock %}
</body>
  • index.html
{% extends "layout.html" %}

{% block body %}
hello world
{% endblock %}
  • 我用
./node_modules/nunjucks/bin/precompile templates >templates.js

templates.js中我有預編譯的代碼。

接下來我應to do來獲得一個正在運行的網絡服務器什么將使用預編譯的template.js

請不要搜索這個問題的任何高級內容。 對於了解節點和 javascript 的人來說,這可能是一個愚蠢的簡單問題。

我所知道的,將需要,創建一個文件讓說app.js並需要與node一起運行它 - 但應該包含什么?

require 'nunjucks';

可能是這樣的: var res = nunjucks.render('templates.js'); 還有什么? (最簡單的(一次性)解決方案)。 注意:要在服務器端而不是在瀏覽器中使用 Nunjucks。

首先初始化Node應用程序,如下所示:

cd njtest
npm init

您可以按“Enter”接受大多數問題的默認值,如果您創建app.js 執行此操作那么它將自動檢測到並將其用作簡單服務器的入口點。

安裝Express:

npm install express --save

然后按如下方式創建app.js

var express     = require( 'express' ),
    app         = express(),
    nunjucks    = require( 'nunjucks' ) ;

// Define port to run server on
var port = process.env.PORT || 9000 ;

// Configure Nunjucks
var _templates = process.env.NODE_PATH ? process.env.NODE_PATH + '/templates' : 'templates' ;
nunjucks.configure( _templates, {
    autoescape: true,
    cache: false,
    express: app
} ) ;
// Set Nunjucks as rendering engine for pages with .html suffix
app.engine( 'html', nunjucks.render ) ;
app.set( 'view engine', 'html' ) ;

// Respond to all GET requests by rendering relevant page using Nunjucks
app.get( '/:page', function( req, res ) {
    res.render( req.params.page ) ;
} ) ;

// Start server
app.listen( port ) ;
console.log( 'Listening on port %s...', port ) ;

現在啟動一個瀏覽器,轉到http:// localhost:9000然后彈出你的頁面!

希望有幫助......

我為 Nunjucks + SCSS + TypeScript 創建了簡單的構建器

文檔: https://github.com/Artik-Man/SamuraiJS

NPM: https://www.npmjs.com/package/samuraijs

npm i samuraijs

創建samurai.js文件:

import {Samurai} from "samuraijs";

new Samurai({
    paths: {
        source: 'src',
        destination: 'dist'
    }
});

將以下行添加到您的 package.json:

{
  "scripts": {
    "serve": "node samurai.js --serve",
    "build": "node samurai.js --build"
  },
  "type": "module"
}

將你的 *.njk 文件放在src/目錄下,運行

npm run serve

並打開localhost:3000

或者npm run build來構建項目。

不要考慮構建配置。 只需編寫您的項目!

我希望我的建造者能解決你的問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM