2012-07-21 11 views
7

तो मैं एक .js फ़ाइलआप फाइल करने के लिए EJS टेम्पलेट्स

var compiled = ejs.compile(source); 
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled); 

में EJS टेम्पलेट्स precompile कराना चाहते थे कि precompile है, लेकिन है कि

function (locals){ 
    return fn.call(this, locals, filters, utils.escape); 
} 

सबसे अच्छा तरीका है precompile करने के लिए क्या और में serilalizes एक .js फ़ाइल में ejs टेम्पलेट्स लिखें

उत्तर

0

आप एक खाली मॉड्यूल के रूप में एक templates.js फ़ाइल (या तो मैन्युअल रूप से या कोड में) बना सकते हैं। फिर टेम्पलेट संकलित करने के बाद, संकलित फ़ंक्शन को खाली मॉड्यूल पर संलग्न किया गया।

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

fs.writeFileSync('./template.js', 'module.exports = { }', 'utf8'); 

var compiled = ejs.compile(fs.readFileSync('./example.ejs', 'utf8')); 

// Add an example function to the template file that uses the compiled function 
require('./template').example = compiled; 

// Get the example template again (this could be in another file for example) 
var output = require('./template').example; 
var html = output({ id: 10, title: 'Output' }); 

modules are cached डिफ़ॉल्ट रूप से के बाद से, आप में सक्षम require('./template.js') को भी आप की जरूरत होनी चाहिए और यह precompiled संलग्न टेम्पलेट्स के सभी होगा।

+1

यह धारावाहिक टेम्पलेट से संबंधित नहीं है, जो वास्तविक प्रश्न था। – Avius

0

Lodash _.template() विधि संकलन के दौरान ईजेएस टेम्पलेट फ़ंक्शन का एक स्ट्रिंग प्रतिनिधित्व बनाता है और संकलित फ़ंक्शन में स्रोत संपत्ति के रूप में संलग्न करता है। आप उस स्ट्रिंग को जेएस फ़ाइल में स्टोर कर सकते हैं, इसे एचटीएमएल में एम्बेड कर सकते हैं, या नींद से पहले अपने पोते को पढ़ सकते हैं।

उदाहरण के लिए:

> var _ = require('lodash'); 
> var compiled = _.template('Hi <%= user %>!'); 
> compiled({ user: 'Axel' }) 
"Hi Axel!" 
> compiled.source 
"function(obj) { 
    obj || (obj = {}); 
    var __t, __p = ''; 
    with (obj) { 
    __p += 'Hi' + ((__t = (user)) == null ? '' : __t) + '!'; 
    } 
    return __p 
}" 
> var fs = require('fs') 
> var src = 'module.exports = ' + compiled.source; 
> fs.writeFileSync('mylittlescript.js', src); 

यह दृष्टिकोण Webpack के ejs-loader मॉड्यूल द्वारा प्रयोग किया जाता है। ध्यान दें कि एनपीएम पैकेज ejs ऐसे स्रोत संपत्ति प्रदान नहीं करता है।

संबंधित मुद्दे