Multi language page with Javascript or jquery

前端 未结 3 1481
臣服心动
臣服心动 2021-01-03 07:53

Currently I am working on web app that will support several languages. Therefore I prepared table in my database with translations. However, I am not sure how to populate we

3条回答
  •  情书的邮戳
    2021-01-03 08:22

    I have faced the same problem many times where the translation has to be handled with JavaScript. The best solution I came up with is to send translation object from the server to the front-end. I will give you an example

    First create folder with translation files. Than create another file where you can handle the translation. It purpose is to generate a JavaScript object which will be send to the front-end. In my case it was a PHP server so I created a file named translation.js.php

    /languages/en.php

     "Hello World",
        "result" => "result",
        "all" => "all",
        "brand" => "brand"
    ];
    

    /languages/bg.php

     "Здравей Свят!",
        "result" => "ресултати",
        "all" => "всички",
        "brand" => "марки"
    ];
    

    /translation.js.php

    Than in your header of footer include the translation.js.php file depending on your business logic. In my case I needed to translate only content which was dynamically create with JavaScript so I handled it the the footer.php file

    ...
    
    
    
    

    And last you main.js file

    console.log(translate)
    // how lets set the heading using jQuery
    $('h1#main_heading').html(translate.hello_world)
    

提交回复
热议问题