Skip to content

How can I translate strings dynamically? #274

@TechOverflow

Description

@TechOverflow

I'm having trouble translating strings dynamically. It seems that this is because the translation is loaded after the rest of the code.

main.js (script linked in head)

function _T(key) {
    'use strict';
    var i18n = $.i18n();
    $.i18n().load('../assets/lang/ui_' + $.i18n().locale + '.json', $.i18n().locale).done(function() {
        console.log(key + ' : ' + $.i18n(key));
        return $.i18n(key);
    });
}

page.php

<script type="text/javascript">
    $(document).ready(function () {
        var formats = { portrait : _T('text-portrait'), landscape : _T('text-landscape'), square : _T('text-square') }
        $.each(formats, function (key, format) {
            console.log('appending '+key)
            $('#format').append($('<option>', { 
                value: key,
                text : format
            }))
        })
    })
</script>

console output:

[Log] appending portrait
[Log] appending landscape
[Log] appending square
[Log] text-portrait : Portrait
[Log] text-square : Square
[Log] text-landscape : Landscape

As you can see, the translation happens after the each loop.
What is the correct way to preload the translation to ensure it being available when document is ready?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions