Search code examples
javascripthtmlinternationalizationtwiggettext

How to make i18n in single js and twig js app


How to make i18n in single js and twig js app? Can't find solution to translate twig.. In angular used angular-gettext but it's not ng app.. Need similar solution for not ng app.. Maybe there is any solution?


Solution

  • solved by including angular gettext

    gulpfile:

    const gulp = require('gulp');
    const gettext = require('gulp-angular-gettext');
    
    gulp.task('extract', function () {
        return gulp.src(['src/**/*.html', 'src/**/*.js'])
            .pipe(gettext.extract('template.pot'))
            .pipe(gulp.dest('translations/'));
    });
    
    gulp.task('translations', function () {
        return gulp.src(['translations/*.po'])
            .pipe(gettext.compile({
                format: 'json'
            }))
            .pipe(gulp.dest('src/i18n'));
    });
    

    js

    const fs = require('fs');
    const phrases = JSON.parse(fs.readFileSync('src/i18n/zh.json', 'utf8'));
    const gettext = (text) => phrases.zh[text] || text;
    
    Twig.extendFilter('translate', gettext);
    

    decorating

    js -

    page().find('.dashboard-mentions').html(gettext("You haven't been mentioned yet."));
    

    html -

    <h4 class="text-label">{{ 'Title *' | translate }}</h4>