Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multilingual Jade templates?

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.

like image 728
Jerome Dahdah Avatar asked Sep 27 '22 01:09

Jerome Dahdah


1 Answers

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).

like image 148
Simon Avatar answered Oct 20 '22 19:10

Simon