Plates 的想法很棒,但远未完成。这是一个解决方案。
应用程序.js
var fs = 需要('fs'); var 盘子 = 要求('盘子'); var flatiron = require('flatiron'); var app = flatiron.app;
app.use(flatiron.plugins.http);
app.router.get('/', function(){
var html = fs.readFileSync('index.html', 'utf-8');
var map = plates.Map();
var data = {"GA_ACCOUNT_CODE": "YOUR_CODE_FROM_CONFIG"}
map.where('data-ga').is('GA_ACCOUNT_CODE').insert('GA_ACCOUNT_CODE');
html = plates.bind(html, data, map);
this.res.html(html);
});
app.start(3000);
索引.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script id="googleAnalytics" data-ga="GA_ACCOUNT_CODE">
var GA_ACCOUNT_CODE = document.getElementById('googleAnalytics').getAttribute('data-ga');
var _gaq=[['_setAccount',GA_ACCOUNT_CODE],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
另一种方法就是这样的 string.replace() :
var html = fs.readFileSync('index.html', 'utf-8');
html = html.replace('GA_ACCOUNT_CODE', 'YOUR_CODE_FROM_CONFIG');
this.res.html(html);
看看cheerio以获得支持。它就像任何其他 css 选择器和 dom 操作前端库一样,只是后端。