I have div that displays a content from mysql database. The content is too long so I decided to use Handlebar helpers. Here is my html code:
<div class="row">
{{#if news}}
{{#each news}}
<div class="col-md-4 img-portfolio">
<a href="/news-details/{{id}}">
<img class="img-responsive img-hover small-img" src="/images/news/{{image}}" alt="">
</a>
<h3>
<a href="/news-details/{{id}}">{{title}}</a>
</h3>
<p> {{substr "10" text}} </p>
</div>
{{/each}}
{{else}}
<p>No News</p>
{{/if}}
The Handlebar Helper is placed in index.js file as follows:
Handlebars.registerHelper('substr', function(length, context, options) {
if ( context.length > length ) {
return context.substring(0, length) + "...";
} else {
return context;
}
});
When I run the nodejs server, I receive "Handlebar is not defined" error. I installed express-handlebar package and also declared it on the index.js file as
var Handlebar = require('express-handlebars');
But it still didn't work.
答案 0 :(得分:1)
You need to use Handlebars
as variable name instead of Handlebar
.
Also, official express-handlebars documentation for helpers suggest do define helpers under exphbs.create
.
So the code with helper on the server should be like:
var exphbs = require("express-handlebars"); // you can use any variable name
var hbs = exphbs.create({
helpers: {
substr: function(length, context, options) {
if (context.length > length) {
return context.substring(0, length) + "...";
} else {
return context;
}
}
}
});
答案 1 :(得分:0)
嗯,这不是一个“正确”的答案,但它使问题得以解决。我用CSS来使它工作。我只是为段落标记添加了一个ID作为“test”,并在style.css文件中分配css,如下所示:
#test {
-o-text-overflow: ellipsis; /* Opera */
text-overflow: ellipsis; /* IE, Safari (WebKit) */
overflow:hidden; /* don't show excess chars */
white-space:nowrap; /* force single line */
width: 350px; /* fixed width */
}