Multilingual Jade Templates?

I use the Jade template engine with gulp, gulp-jade and gulp-data to create a very simple one page website in two languages. The result should be static HTML documents without further processing on the server side or on the client side. Is it possible to load website content from a JSON file depending on the language that I define in my index.jade , and what would be the best way to do this?

My current attempt is throwing 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 

When running gulp:

The following error occurs:
 Cannot read property 'foo' of undefined 

I do not mind splitting JSON into different files into one language, if it simplifies, but I have no idea how to include the corresponding file from index_en.jade .

Some context:

I should note that I am expanding the default layout file ( default.jade ), which itself includes a bunch of things like header.jade and footer.jade so that the template system is as dry as possible. These files should also be multilingual, so I would like to define lang="en" in my index_en.jade , lang="de" in index_de.jade and just pass this to all other particles without duplication the same (for example, not header_de.jade or such).

I also combine these functions back into the yoman generator, so I would like to find a system in which I can avoid having to adjust gulpfile.js if I have to add another language later.

+5
source share
1 answer

The error lies in #{lang.foo} . You set lang to a string and there is no foo on it ... If you install lang on the actual object that you are 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: a variable declaration must be inside a block (sometimes).

+4
source

Source: https://habr.com/ru/post/1237411/


All Articles