kiran
kiran

Reputation: 193

How to use translate in javascript file in Zend Framework?

How to use translate in JavaScript file?

I have a formatter.js file:

function xyz(id)
{
    if(confirm("Vill du radera ?")){
        location.href = "/student/files/delete/" + id;
    }
}

Here I want to use a translation for "vill du radera?".

In my view.phtml file I use something like this:

<?=$this->translate->_("Select Template")?> 

It's working fine ...

Upvotes: 0

Views: 2180

Answers (3)

Jesper Johansson
Jesper Johansson

Reputation: 81

It is also a ide to save your js file as .php and include it in the view. Of course you need to wrap the javascripts with tags. But the best part is that it would work to use for example:

     <script>
     var text = '<?php echo $this->translate('string that would be in JavaScript');?>';
     </script>

The advantages of this way is that you will have all translations in one place

Upvotes: 0

Amrish Prajapati
Amrish Prajapati

Reputation: 787

AS you are using this:

function xyz(id)
{
    if(confirm("Vill du radera ?")){
        location.href = "/student/files/delete/" + id;
    }
}

You must be calling it from .phtml file.

You can do one thing :

you can call function xyz() with two parameters (1) id and (2) translate variable

in .phtml file

xyz("<?php echo id;?>","<?php echo $this->translate->_("Select Template")?>");

in .js file

function xyz(id,translate)
{
    if(confirm(translate)){
        location.href = "/student/files/delete/" + id;
    }
}

Try it.

Upvotes: 1

bububaba
bububaba

Reputation: 2870

If you do few translations in your *.js included files, you can just set a JS variable in your view when you know what keys will be used, for example:

//viewscript:
<script ...>
    var translation = <?php echo Zend_Json::encode($this->translate->_("Select Template")) ?>;
</script>

You will just need to make sure the variable is available before it is needed.

But if you need to do many translations, one approach would be to add a translate(key) function in your *.js file. This function would do an AJAX call to retrieve either a single key translation, or - preferably - many/all translations and store them in a variable, so that the round-trip to the server is done only once - on the first translation.

//*.js
var translations = null;
function translate(key) {
    if (translations !== null) {
        return translations[key];
    }
    else {
        //use AJAX to get translations from server: /translations/serve-json
        // ...
        translations = ajaxData;
        return translations[key];
    }
}

And here's the controller:

//TranslationsController (for example)
public function serveJsonAction() {
    //get translations first
    // ...
    $this->_helper->json($translations);
}

Final use would be:

function xyz(id)
{
    if(confirm(translate("VILL_DU_RADERA"))){
        location.href = "/student/files/delete/" + id;
    }
}

Upvotes: 1

Related Questions