Javascript 部分使用 Node.js + Express + Hogan.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12783615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:15:18  来源:igfitidea点击:

Partials with Node.js + Express + Hogan.js

javascriptnode.jsexpressviewenginehogan.js

提问by

I'm developing a site with Node.js + Express and using as view engine Hogan.js.

我正在使用 Node.js + Express 开发一个站点,并将其用作视图引擎 Hogan.js。

This is my file app.js:

这是我的文件app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'hjs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(app.router);
  app.use(require('less-middleware')({ src: __dirname + '/public' }));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

The file /routes/index.jsis:

该文件/routes/index.js是:

/*
 * GET pages.
 */

exports.index = function(req, res){
  res.render(
    'index',
    {
      title: 'Home Page',
      author: 'Bruce Wayne'
    }
  );
};

exports.about = function(req, res){
  res.render(
    'about',
    {
      title: 'About Page',
      author: 'Bruce Wayne'
    }
  );
};

In /viewsfolder, there are:

/views文件夹中,有:

|- part.hjs

|- part.hjs

|- index.hjs

|- index.hjs

|- cv.hjs

|- cv.hjs

The file part.hjsis:

该文件part.hjs是:

<h3>Hello {{ author }}</h3>

The file index.hjsis:

该文件index.hjs是:

<h1>Title: {{ title }} </h1>
{{> part }}
Welcome to Gotham City.

And the file about.hjsis:

该文件about.hjs是:

<h1>Title: {{ title }}</h1>
{{> part }}
I'm not Joker.

I've two questions:

我有两个问题:

  1. How can I use properly the partials in my pages? (this code doesn't work)
  2. Can I use the same "title" for two or more pages without repeat the values assignment in file /routes/index.js?
  1. 如何正确使用页面中的部分?(此代码不起作用)
  2. 我可以在两个或多个页面上使用相同的“标题”而不重复文件中的值分配/routes/index.js吗?

Best regards, Vi.

最好的问候,维。

回答by

I've found a solution for the first question.

我找到了第一个问题的解决方案。

First of all, I removed hjs:

首先,我删除了hjs

npm remove hjs

Then, I installed the package hogan-express:

然后,我安装了软件包hogan-express

npm install hogan-express

Furthermore, I edited app.js:

此外,我编辑app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.engine('html', require('hogan-express'));
app.enable('view cache');

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'html');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(app.router);
  app.use(require('less-middleware')({ src: __dirname + '/public' }));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

And routes/index.js:

并且routes/index.js

exports.index = function(req, res) {
  res.locals = {
    title: 'Title',
  };
  return res.render(
    'index',
    {
      partials:
      {
        part: 'part',
      }
    }
  );
};

Now, in /viewsthere are index.html, part.html. The file part.htmlcontains:

现在,/viewsindex.html, part.html。该文件part.html包含:

<h1>{{ title }}</h1>

The file index.htmlcontains:

该文件index.html包含:

{{> part}}
Hello world!

So, It works fine.

所以,它工作正常。

回答by bryanmac

At least in Express 4+, partials just work out of the box. You can use express-generator (from npm) with --hogan or -H option.

至少在 Express 4+ 中,partials 是开箱即用的。您可以使用带有 --hogan 或 -H 选项的 express-generator(来自 npm)。

After doing that, you need to add partials to the render method:

这样做之后,您需要向渲染方法添加部分:

router.get('/', function(req, res, next) {
  res.render('index', 
        { 
            title: 'My Site',
            partials: {header: 'header'} 
        });
});

Then, in your template use {{ > xxx }}

然后,在您的模板中使用 {{ > xxx }}

<body>
  {{> header }}
  <h1>{{ title }}</h1>

  <p>Welcome to {{ title }}</p>
</body>

NOTE: this has header.hjs in views

注意:这在视图中有 header.hjs

回答by Oren Yakobi

To use partials with express+hogan, just do the following:

要在 express+hogan 中使用分音,只需执行以下操作:

app.get('/yourRoute', function(req, res){  
   res.render('yourPartial', function(err,html){
       var partialHTML = html;
       res.render('yourMainView', { myPartial: partialHTML }, function(err,html){
          res.send(html);   
       });     
   });
}

And now, yourMainView.html:

现在,你的MainView.html:

<p>Something Something Something</p>
{{{partialHTML}}}
<p>Bla Bla Bla</p>

Notice the triple '{' instead of double as you usually do! That telling hogan (mustache) to parse this as HTML rather then a string!

请注意三重“{”而不是您通常做的双!告诉 hogan (mustache) 将其解析为 HTML 而不是字符串!

That's it.

就是这样。

回答by ydaniv

As for your partials question, if you use consolidate.jsyou can simply do:

至于你的部分问题,如果你使用consolidate.js你可以简单地做:

res.render('index', {
  partials: {
    part  : 'path/to/part'
  }
});

回答by Josh

This is a problem. Partial support is difficult to come by in Express 3.

这是个问题。在 Express 3 中很难获得部分支持。

Your best bet is: https://github.com/visionmedia/consolidate.jsnpm install consolidate

您最好的选择是:https: //github.com/visionmedia/consolidate.jsnpm install consolidate

These patches take different approaches to adding partials for Hogan:

这些补丁采用不同的方法为 Hogan 添加分音:

Unfortunately, the engine doesn't have a hook for filesystem based partials natively, so I think people are confused about how and where partials should be implemented. I ended up with LinkedIn's Dust.js implementation, since partial support was already there. Master actually has even better support, plus I submitted a patch yesterday for relative paths.

不幸的是,引擎本身没有针对基于文件系统的部分的钩子,所以我认为人们对应该如何以及在何处实现部分感到困惑。我最终使用了 LinkedIn 的 Dust.js 实现,因为部分支持已经存在。Master实际上有更好的支持,加上我昨天提交了一个相对路径的补丁。

Josh

乔希

回答by Jonathan Hawkes

I would use mmminstead of hjs.

我会使用mmm而不是hjs.

https://github.com/techhead/mmm

https://github.com/techhead/mmm

Disclaimer: I wrote the package.

免责声明:我写了这个包。

Just replace all occurrences of hjswith mmmand partials will start working. There is a lot more information and an example at the link above.

只需替换所有出现的hjswithmmm和部分将开始工作。上面的链接中有更多信息和示例。

As for your other question, if you want to share properties across multiple views, you have a couple of options.

至于你的另一个问题,如果你想跨多个视图共享属性,你有几个选择。

When you call res.render(name, options), the optionswill actually be merged onto res.localsand app.localsbefore being passed to the rendering engine. Therefore to set an app-wide property, you can simply assign it to app.locals.

当您调用 时res.render(name, options)options实际上将在传递给渲染引擎之前res.localsapp.locals之前合并。因此,要设置应用程序范围的属性,您只需将其分配给app.locals.

app.locals.title = "Default Title"; // Sets the default title for the application

This concept really applies to just about any Express 3 View Engine.

这个概念真的适用于几乎所有的 Express 3 视图引擎。

However, for mmmspecifically, please see the section under Presentation Logic for more ways to bind values to a template or set of templates.

但是,mmm具体而言,请参阅表示逻辑下的部分,了解将值绑定到模板或模板集的更多方法。