How do I load different partials dynamically using handlebars templates?

后端 未结 3 663
慢半拍i
慢半拍i 2021-01-31 05:46

I\'m loading a template with the following data:

\"slides\": [
    {
        \"template\": \"video\",
        \"data\": {
            \"video\": \"\"
        }
          


        
3条回答
  •  醉酒成梦
    2021-01-31 05:59

    I found the above answers a little hard to understand - they leak globals, have single character variables, and some odd naming. So here's my own answer, for my (and your) reference:

    A dynamic partial using 'hbs', express.js default handlebars implementation:

    I used this to make a simple blog making (article-name).md into /blog/(article-name), creating a dynamic partial:

    // Create handlebars partials for each blog item
    fs.readdirSync('blog').forEach(function(blogItem){
        var slug = blogItem.replace('.md','')
        var fileContents = fs.readFileSync('blog/'+blogItem, 'utf8')
        var html = marked(fileContents)
        var compiledTemplate = hbs.compile(html);
        hbs.registerPartial(slug, compiledTemplate);
    })
    
    // Create 'showBlogItem' helper that acts as a dynamic partial
    hbs.registerHelper('showBlogItem', function(slug, context, opts) {
        var loadedPartial = hbs.handlebars.partials[slug];
        return new hbs.handlebars.SafeString(loadedPartial(context));
    });
    

    Here's the route. It 404s if the partial doesn't exist, because the blog doesn't exist.

    router.get('/blog/:slug', function(req, res){
        var slug = req.param("slug")
        var loadedPartial = hbs.handlebars.partials[slug];
        if ( ! loadedPartial ) {
            return res.status(404).json({ error: 'Article not found' })
        }
        res.render('blog', {
            slug: slug
        });
    })
    

    /views/blog.hbs looks like:

    {{ showBlogItem slug }}

提交回复
热议问题