node.js - 在 Sails 中实现自定义 i18n 片段

标签 node.js sails.js

现有的 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 以支持此类片段的最佳方式是什么?

  1. 如何向 View 层公开 fragment 函数?我在哪里定义这个函数?
  2. 如何获取当前事件区域设置以便了解要加载哪个文件?

最佳答案

图书馆

我创建了a library处理这样的用例。下面的代码已合并到该库中。

解决方案

  1. fragment 函数可以使用 Expresses res.locals 公开属性(property)。您可以通过 routes 在钩子(Hook)中访问它。

  2. 当前区域设置通过 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/

相关文章:

node.js - 是否可以在sails.js/waterline 中重命名 `createdAt` 和 `updatedAt`

javascript - 如何在 watch 模式下 sails (开发中)

node.js - 从 angular2 服务发送正文中的值

javascript - try-catch 应该如何与多个事件处理程序一起使用?

javascript - 我无法在 Sails.js 上建立简单的关联(关系模型的字段显示未定义)

javascript - 将数据从 Sails 服务发送到 Controller

node.js - 谷歌API日历 watch 不起作用,但 channel 已创建

node.js - 如何使用 mongoose 聚合函数计算每个评分

node.js - 你如何在 Mongoose 中将 _id 从 ObjectID 更改为 Number

mongoose - Sails.js - 是否可以完全使用 'turn off' 水线模块或使用 mongoose 而不是使用 sails-mongo?