简体   繁体   中英

gettext translation in PHP works fine, but not with javascript

I use gettext in combination with *.po and *.mo files to translate my little website into different languages. User can chose on a dropdown their preferred language, the site gets refreshed and the chosen language is shown.

When it comes to translate javascript content that appears when user interacts (for example: a note to type minimum 6 characters below the input field) I dont know how to solve it properly. Is there an easy way how to get that notes also with gettext like in php translated? I read here a lot about it and tried what I could, but somehow I cant figure it out.

Here is the simplified index.js code:

let messageUserText;
let userInput;

messageUserText     = document.getElementById('userMsg');
userInput           = document.getElementById('usernameInput');

function validInput() {
    const userName      = usernameInput.value;

    let messageUserName = '';

    if (userName === '') {
        messageUserName = 'Please enter username';
    } else if (userName.search(/[^a-zA-Z0-9üÜöÖäÄ]/) === -1) {
        messageUserName = 'Username accepted';
    } else {
        messageUserName = 'Please check username';
    }
    messageUserText.innerHTML = messageUserName;
}

This is the simplified code in index.php:

<?php
   require_once("locale.php");
   include_once('header.php');
?>
...
<!-- DROPDOWN LANGUAGE SELECTION -->
        <form name="locale" action="index.php" method="POST">
              <button type="button" class="dropdown">
                      <!-- SHOW CHOSEN LANGUAGE -->
                      <?php 
                        if (isset($_POST['locbtn'])) {
                          if ($_POST['locbtn'] === 'en_EN') {
                            echo "EN";
                          } else if ($_POST['locbtn'] === 'de_DE') {
                            echo "DE";
                          }
                        }
                        else {
                          echo "EN";
                        }?>
              </button>
              <ul class="dropdown-menu">
                <li><button class="item" type="submit" value="en_EN" name="locbtn"><?php echo _("DE"); ?></button></li>
                <li><button class="item" type="submit" value="de_DE" name="locbtn"><?php echo _("EN"); ?></button></li>
              </ul>
            </form>
   ...
          <!-- INPUT FORM -->
          <div>
            <form>
              <!-- Floating Labels INPUT USER -->
                  <input type="text" 
                     placeholder="<?php echo _("Username"); ?>" 
                     aria-label="<?php echo _("Username"); ?>" 
                     id="usernameInput" 
                     onkeyup="validInput()" 
                   required>
                  <label for="usernameInput">
                     <?php echo _(" Username"); ?>
                  </label>  
              <!-- NOTE MESSAGE: THIS IS WHERE I CANT TRANSLATE APPEARING JAVASCRIPT CONTENT-->
               <p id="userMsg"></p>
    ...
    <!-- Javascripts-->
       <script type="text/javascript" src="includes/js/index.js"></script>

    <?php include('footer.php'); ?>

This is the locale.php

    <?php
        //Locale Main & HTML Handler
        if (isset($_POST['locbtn'])) {
            
            $locale = $_POST['locbtn'];
                      
            if ($_POST['locbtn'] === 'en_EN') {
                $htmlLanguage = 'en';
            } else if ($_POST['locbtn'] === 'de_DE') {
                $htmlLanguage = 'de';
            }
        } else {
            $htmlLanguage = 'en';
            $locale = 'en_EN';
        }

       // Set lang env
       putenv("LANGUAGE=$locale");

       // Set locale:
       setlocale( LC_MESSAGES, $locale);

       // Name of translation files
       $domain = 'test';

       // Set the path for a domain
       $pathToDomain = "/home/locale/";
       bindtextdomain($domain, $pathToDomain);

       // Set codeset
       bind_textdomain_codeset($domain, 'UTF-8');

       textdomain($domain);
    ?>

Here is a basic example using an object to create a key/value pair of the translations per language.

 let selected_lang = "en"; //use cookies, localstorage or even php to hardcode the language that they previously selected let translations = {}; translations["en"] = { "username-empty": "Please enter username", "username-valid": "Username accepted", "username-unknown": "Please check username" }; translations["de"] = { "username-empty": "GERMAN Please enter username", "username-valid": "GERMAN Username accepted", "username-unknown": "GERMAN Please check username" }; function getTranslation(field){ return translations[selected_lang][field]; } function validInput() { const userName = usernameInput.value; let messageUserName = ''; if (userName === '') { messageUserName = getTranslation("username-empty"); } else if (userName.search(/[^a-zA-Z0-9üÜöÖäÄ]/) === -1) { messageUserName = getTranslation("username-valid"); } else { messageUserName = getTranslation("username-unknown"); } messageUserText.innerHTML = messageUserName; } console.log(getTranslation("username-unknown"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM