ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 384 forks source link

render a string html #240

Open lugomulish opened 5 years ago

lugomulish commented 5 years ago

'm creating a site with express using handlebars for the template engine.

In this project I want to the give to the users the hability of modify the HTML of the final views..

If the user specify a custom html for view we save the full html in a database and use it when the page is loading.

So, i need to use the two schemas for render the vews:

1.- Normals scheme of handlebars (just pass the path of the file.hbs)

2.-Pass the HTML-String and render it.

This is my expected code:

`

 router.get('/products/:product_slug', function(req, res, next) {

 //Get custom html from db

var CustomHtml?getCustomHtml():false;

Product.find(function(err, products){

if(CustomHtml){

    //How can I print the custom html¿?¿?¿?

    res.renderHTMLSTRING(CustomHtml, { title: 'Mondo', products: products });

}else{
    //Default behaviour of hbs
    res.render('default/product/index', { title: 'Mondo', products: products });
}});});

`

any suggestion?

timaschew commented 5 years ago

What is custom HTML?
Why you're passing an object to it? That sounds very weird and makes no sense.

sychdo commented 4 years ago

As far as i understood you need smth like this:

// i would recommend to do it once somewhere in 'config/hbs.js' and then import handlebars instance anytime you need it.
const exphbs = require('express-handlebars');
const hbs = exphbs.create({ /* your config */ });

...

const templateString= `<h1>Home page</h1>
    <div>{{title}}</div>
    {{#each products}}
        <div>
            {{this.id}}
        </div>
        <div>
            {{this.title}}
        </div>
    {{/each}}`;

const template = hbs.handlebars.compile(templateString);
const result = template({
    title: 'some title',
    products: [{ id: 1, title: 'title 1' }, { id: 2, title: 'title 2' }]
});

variable 'result' now contains compiled html with passed context.