Multilingual Jade templates?

穿精又带淫゛_ 提交于 2019-12-10 13:46:26

问题


I'm using the Jade template engine with gulp, gulp-jade and gulp-data to build a very basic one-page website in two languages. The result should be static HTML documents with no further server-side or client-side processing. Is it possible to load website content from a JSON file depending on a language I define in my index.jade, and what would be the best way to go about doing this?

My current attempt causes an error:

gulpfile.js:

gulp.task('views', function () {
  return gulp.src('app/**/*.jade')
    .pipe($.data(function(file) {
      return require('./app/data/text.json'); // load language file
    }))
    .pipe($.jade({pretty: true, basedir: 'app/'}))
    .pipe(gulp.dest('.tmp'));
});

text.json:

{
  "de": {
    "foo": "deutsch"
  },

  "en": {
    "foo": "english"
  }
}

index_en.jade:

extends /_layouts/default.jade

var lang = "en"

block content

    h1 #{lang.foo} // load text from json

This results in the following error when I run gulp:

Cannot read property 'foo' of undefined

I don't mind splitting up the JSON into different files per language if that makes things easier, but I have no idea how I would include the appropriate file from within index_en.jade.

Some context:

I should note that I'm extending a default layout file (default.jade), which itself includes a bunch of things like header.jade and footer.jade to keep the template system as DRY as possible. Those files would need to be multilingual as well, which is why I would like to define lang="en" in my index_en.jade, lang="de" in index_de.jade, and just have that propagate to all of the other partials without having to duplicate those as well (e.g. no header_de.jade or such).

I'm also merging these features back into my yeoman generator, so I would like to find a system where I can avoid having to adjust gulpfile.js if I were to add another language later on.


回答1:


The error lies in #{lang.foo}. You've set lang to a string and that doesn't have a foo on it… If you set lang to the actual object that you're loading (en or de in this case), it works fine:

extends /_layouts/default.jade

block content

    - var lang = en

    h1 #{lang.foo} // load text from json

Note the missing quotation marks.

Edit: Variable declaration needs to be inside block (sometimes).



来源:https://stackoverflow.com/questions/34090945/multilingual-jade-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!