现有的 i18n
服务在 Sails 中对于短字符串和消息来说非常好,但是,我想将模板的一部分提取到 Markdown 格式的所谓片段中,并从模板中获取它们。
我创建了以下结构:
- locales/fragments/en/index/introduction.md
- locales/fragments/ru/index/introduction.md
现在我想根据模板中的事件区域设置包含以下片段之一:
<section class="introduction">
<h2>Introduction</h2>
{{ fragment('index.introduction') }}
</section>
扩展 Sails 以支持此类片段的最佳方式是什么?
- 如何向 View 层公开
fragment
函数?我在哪里定义这个函数? - 如何获取当前事件区域设置以便了解要加载哪个文件?
最佳答案
图书馆
我创建了a library处理这样的用例。下面的代码已合并到该库中。
解决方案
fragment
函数可以使用 Expressesres.locals
公开属性(property)。您可以通过routes
在钩子(Hook)中访问它。当前区域设置通过
req.getLocale()
公开功能。
这是我生成的钩子(Hook)的完整代码:
module.exports = function (sails) {
var deasync = require('deasync');
var fs = require('fs');
var marked = require('marked');
var configKey = 'i18n-fragment';
var activeLocale;
var defaults = {};
defaults[configKey] = {
path: 'locales/fragments/{locale}/{path}.md'
};
return {
defaults: defaults,
routes: {
before: {
'/*': function (request, response, next) {
if (request.accepted.some(function (type) {
return type.value === 'text/html';
})) {
activeLocale = request.getLocale();
response.locals.fragment = deasync(getFragment);
}
next();
}
}
}
};
function getFragment (address, callback) {
var path = getFragmentPath(address, activeLocale);
fs.readFile(path, 'utf8', function (error, source) {
if (error) {
return callback(error);
}
marked(source, callback);
});
}
function getFragmentPath (address, locale) {
return sails.config[configKey].path
.replace('{locale}', locale)
.replace('{path}', address.replace('.', '/'))
;
}
};
关于node.js - 在 Sails 中实现自定义 i18n 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31492144/