2011-11-09 13 views
21

Sto utilizzando il file handlebars hbs wrapper in express.js. Ho dei modelli che funzionano bene, ma ho bisogno di aggiungere parziali da renderizzare con le mie viste.Modulo hbs di Express.js - registrazione parziali dal file .hbs

mi piacerebbe fare qualcosa di simile:

hbs.registerPartial('headPartial', 'header'); 
// where "header" is an .hbs file in my views folder 

Tuttavia, è gettare un "header parziale non può essere trovato".

Posso rendere il lavoro registerPartial se si passa una stringa di html al secondo param, ma mi piacerebbe utilizzare file di visualizzazione separati per i miei parziali.

Non ho trovato alcuna documentazione su questo, ma spero che mi manchi solo qualcosa di facile.

Qualcuno sa come utilizzare i file di visualizzazione nel metodo registerPartial? Se sì, come posso implementarlo?

UPDATE

per dare più contesto, permettetemi di aggiungere più codice. Ecco il mio file "server" - app.js

var express = require('express') 
, routes = require('./routes') 
, hbs = require('hbs'); 

var app = module.exports = express.createServer(); 

// Configuration 

app.configure(function(){ 
    app.set('views', __dirname + '/views'); 
    app.set('view engine', 'hbs'); 
    app.use(express.bodyParser()); 
    app.use(express.methodOverride()); 
    app.use(app.router); 
    app.use(express.static(__dirname + '/public')); 
}); 

app.configure('development', function(){ 
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
}); 

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

// this is the line that generates the error 
hbs.registerPartial('headPartial', 'header'); 

// What I'm expecting is for "headPartial" to be a compiled template partial 
// of the template within views/header.hbs, but it is not loading this way. 
// If I do something like hbs.registerPartial('headPartial', '<p>test</p>'); 
// then it does work. I need to know how to pass an .hbs file to the 
// registerPartial method. 

// Routes 
app.get('/', routes.index); 

app.listen(3000); 

e qui è il mio file routes.index:

exports.index = function(req, res){ 
    res.render('index', { title: 'Express' }) 
}; 

Nella mia cartella di vista, ho tre modelli:

views/ 
    header.hbs (this is my partial) 
    index.hbs 
    layout.hbs 

Nel mio file index.hbs, sto chiamando il partial 'headPartial' con:

{{> headPartial}} 

Qualsiasi aiuto è molto apprezzato.

risposta

36

Questo code carica tutti i modelli parziali in una directory e le rende disponibili per nome file:

var hbs = require('hbs'); 
var fs = require('fs'); 

var partialsDir = __dirname + '/../views/partials'; 

var filenames = fs.readdirSync(partialsDir); 

filenames.forEach(function (filename) { 
    var matches = /^([^.]+).hbs$/.exec(filename); 
    if (!matches) { 
    return; 
    } 
    var name = matches[1]; 
    var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8'); 
    hbs.registerPartial(name, template); 
}); 
+1

Nizza. Un modo rapido per avere tutti i partial disponibili quando necessario! – swatkins

+0

Grazie Ben, questo mi ha davvero aiutato molto. – Dave

11

Sembra la creazione di una variabile e tirando in codice del modello manualmente funziona:

var hbs = require('hbs') 
    , fs = require('fs') 
    , headerTemplate = fs.readFileSync(__dirname + '/views/_header.hbs', 'utf8'); 

e versioni successive:

hbs.registerPartial('headPartial', headerTemplate); 
+0

Grazie per questo, funziona alla grande – iancrowther

+0

questo sembra un sacco di lavoro extra di citare in giudizio i parziali in Express3 – chovy

35

Per comodità, registerPart IALS fornisce un modo rapido per caricare tutti i parziali da una directory specifica:

var hbs = require('hbs'); 
hbs.registerPartials(__dirname + '/views/partials'); 

partial che vengono caricati da una directory vengono denominati in base al loro nome, dove gli spazi e trattini vengono sostituiti con un carattere di sottolineatura:

template.html  -> {{> template}} 
template 2.html -> {{> template_2}} 
login view.hbs  -> {{> login_view}} 
template-file.html -> {{> template_file}} 

Cheers!

+0

Ciao, funzionerà anche per le sottodirectory? In questo caso, come possiamo ottenere le visualizzazioni? Grazie –

+0

Questo è ottimo, ma si tenga presente che carica partial in modo asincrono con un callback - probabilmente non si accettano richieste fino a quando non viene completato: [Helpers e Partial] (https://github.com/pillarjs/hbs # aiutanti-e-parziali) –

1

Per me avevo il file di modello mio-parziale.hbs

Poi cercato di accedervi attraverso:

{{> my-partial }} 

Ma il parziale è stato immagazzinato in hbs come my_partial indipendentemente dal nome del file.

, grazie ad hbs versione 3.1.0 linea 218

.slice(0, -(ext.length)).replace(/[ -]/g, '_').replace('\\', '/'); 

Questo è nel readme

0

Per quanto mi riguarda, ho una funzione come:

var hbs = require('hbs'); 
var fs = require('fs');  
var statupfunc = { 
     registerHbsPartials : function(){ 
     //this is run when app start 
     hbs.registerPartials(__dirname + "/" + resource.src.views + '/partials');   
     }, 
     registerOneHbsPartials : function(event){ 
     //this is run for gulp watch 
     if(event.type == 'deleted') 
     { 
      return; 
     } 
     var filename = event.path; 
     var matches = /^.*\\(.+?)\.hbs$/.exec(filename); 
     if (!matches) { 
      return; 
     }  
     var name = matches[1];  
     var template = fs.readFileSync(filename, 'utf8');  
     hbs.registerPartial(name, template);  
     } 
    }; 

Run statupfunc .registerHbsPartials all'avvio dell'app e quindi registrare gulp watch con statupfunc.registerOneHbsPartials per registrare parziali sulla nuova creazione

gulp.task('watch', function() { 
    gulp.watch(resource.src.views + '/partials/*.*', statupfunc.registerOneHbsPartials); 
}); 
Problemi correlati