Exemple de traducteur de blocs/balises simple

Pour vous aider à comprendre la traduction, regardez un traducteur entièrement écrit en JavaScript, qui n'utilise de bibliothèque C pour aucune fonctionnalité. Le traducteur suivant serait plus efficace s'il était écrit en C, mais la version JavaScript est plus simple et constitue de ce fait un exemple idéal pour illustrer le fonctionnement des traducteurs.

Comme la plupart des traducteurs, celui-ci est conçu pour émuler le comportement d'un serveur. Supposons que votre serveur Web soit configuré pour remplacer la balise KENT par la photo d'un technicien différent selon le jour de la semaine, l'heure de la journée ou la plate-forme de l'utilisateur. Le traducteur exécute la même opération, mais uniquement localement.

Pour créer le traducteur de blocs/balises :

  1. Créez un document vierge.
  2. Entrez le code suivant :
    <html>
    <head>
    <title>Kent Tag Translator</title>
    <meta http-equiv="Content-Type" content="text/html; charset=">
    <script language="JavaScript">
    /**********************************************************
     * The getTranslatorInfo() function provides information  *
     * about the translator, including its class and name,    *
     * the types of documents that are likely to contain the  *
     * markup to be translated, the regular expressions that  *
     * a document containing the markup to be translated      *
     * would match (whether the translator should run on all  *
     * files, no files, in files with the specified           *
     * extensions, or in files matching the specified         *
     * expressions).                                          *
     **********************************************************/
    function getTranslatorInfo(){
      //Create a new array with 6 slots in it
      returnArray = new Array(6);
      
      returnArray[0] = "DREAMWEAVER_TEAM"					// The translatorClass
      returnArray[1] = "Kent Tags"					// The title
      returnArray[2] = "0" 					// The number of extensions
      returnArray[3] = "1"					// The number of expressions
      returnArray[4] = "<kent"					// Expression
      returnArray[5] = "byExpression"					// run if the file contains "<kent"
      return returnArray; 
    }
    
    /
    *********************************************************************
    *****
    * The translateMarkup() function performs the actual translation.         
    *
    * In this translator, the translateMarkup() function is written           
    *
    * entirely in JavaScript (that is, it does not rely on a C library) --    
    *
    * and it's also extremely inefficient. It's a simple example, however,    
    *
    * which is good for learning.                                             *
    ************************************************************************
    **/
    function translateMarkup(docNameStr, siteRootStr, inStr){
      var outStr = "";                 // The string to be returned after 
    translation
      var start = inStr.indexOf('<kent>');     // The first position of the 
    KENT tag
                                               // in the document.
      var replCode = replaceKentTag();        // Calls the replaceKentTag() 
    function
                                            // to get the code that will replace 
    KENT.
      var outStr = "";                 // The string to be returned after 
    translation
    
       //If the document does not contain any content, terminate the 
    translation.
      if ( inStr.length <= 0 ){
         return "";
      }
      
      // As long as start, which is equal to the location in inStr of the
      // KENT tag, is not equal to -1 (that is, as long as there is another
      // KENT tag in the document)
      while (start != -1){
         // Copy everything up to the start of the KENT tag.
         // This is very important, as translators should never change
         // anything other than the markup that is to be translated.
         outStr = inStr.substring(0, start);
         // Replace the KENT tag with the translated HTML, wrapped in special 
         // locking tags. For more information on the replacement operation, 
    see
         // the comments in the replaceKentTag() function.
         outStr = outStr + replCode;
    
         // Copy everything after the KENT tag.
         outStr = outStr + inStr.substring(start+6);
    
         // Use the string you just created for the next trip through
         // the document. This is the most inefficient part of all.
         inStr = outStr;
         start = inStr.indexOf('<kent>');
    
      }
      // When there are no more KENT tags in the document, return outStr.
      return outStr;
    }
    
    /**************************************************************
    * The replaceKentTag() function assembles the HTML that will  *
    * replace the KENT tag and the special locking tags that will *
    * surround the HTML. It calls the getImage() function to      *
    * determine the SRC of the IMG tag.                           *
    **************************************************************/
    function replaceKentTag(){
      // The image to display.
      var image = getImage();   
      // The location of the image on the local disk.
      var depFiles = dreamweaver.getSiteRoot() + image;
      // The IMG tag that will be inserted between the lock tags.   
      var imgTag = '<IMG SRC="/' + image + '" WIDTH="320" HEIGHT="240" 
    ALT="Kent">\n';
      // 1st part of the opening lock tag. The remainder of the tag is 
    assembled below.
      var start = '<MM:BeginLock translatorClass="DREAMWEAVER_TEAM" 
    type="kent"';
      // The closing lock tag.
      var end = '<MM:EndLock>';
         
      //Assemble the lock tags and the replacement HTML.
      var replCode = start + ' depFiles="' + depFiles + '"';
      replCode = replCode + ' orig="%3Ckent%3E">\n';
      replCode = replCode + imgTag;
      replCode = replCode + end;
      
      return replCode;
    }
    
    /******************************************************************
     * The getImage() function determines which image to display      *
     * based on the day of the week, the time of day and the          *
     * user's platform. The day and time are figured based on UTC     *
     * time (Greenwich Mean Time) minus 8 hours, which gives          *
     * Pacific Standard Time (PST). No allowance is made for Daylight *
     * Savings Time in this routine.                                  *
    ******************************************************************/
    function getImage(){
      var today = new Date();            // Today's date & time.
      var day = today.getUTCDay();       // Day of the week in the GMT time 
    zone.
                                         // 0=Sunday, 1=Monday, and so on.
      var hour = today.getUTCHours();    // The current hour in GMT, based on 
    the
                                         // 24-hour clock.
      var SFhour = hour - 8;             // The time in San Francisco, based 
    on the
                                         // 24-hour clock.
      var platform = navigator.platform; // User's platform. All Windows 
    machines
                                         // are identified by Dreamweaver as 
    "Win32",
                                         // all Macs as "MacPPC".
      var imageRef;                      // The image reference to be returned.
    // If SFhour is negative, you have two adjustments to make. 
       // First, subtract one from the day count because it is already the 
    wee 
       // hours of the next day in GMT. Second, add SFhour to 24 to
       // give a valid hour in the 24-hour clock. 
       if (SFhour < 0){
         day = day - 1;
           // The day count back one would make it negative, and it's 
    Saturday,
           // so set the count to 6.
           if (day < 0){
               day = 6;
           }
         SFhour = SFhour + 24;
       }
       
      // Now determine which photo to show based on whether it's a workday or 
    a 
      // weekend; what time it is; and, if it's a time and day when Kent is 
      // working, what platform the user is on.
      
      //If it's not Sunday
      if (day != 0){
         //And it's between 10am and noon, inclusive
         if (SFhour >= 10 && SFhour <= 12){
            imageRef = "images/kent_tiredAndIrritated.jpg";
          //Or else it's between 1pm and 3pm, inclusive
         }else if (SFhour >= 13 && SFhour <= 15){
            imageRef =  "images/kent_hungry.jpg";
         //Or else it's between 4pm and 5pm, inclusive
         }else if (SFhour >= 16 && SFhour <= 17){
            //If user is on Mac, show Kent working on Mac
            if (platform == "MacPPC"){ 
               imageRef = "images/kent_gettingStartedOnMac.jpg";
            //If user is on Win, show Kent working on Win
            }else{
               imageRef = "images/kent_gettingStartedOnWin.jpg";
            }
         //Or else it's after 6pm but before the stroke of midnight
         }else if (SFhour >= 18){
             //If it's Saturday
             if (day == 6){
               imageRef = "images/kent_dancing.jpg";
            //If it's not Saturday, check the user's platform
            }else if (platform == "MacPPC"){ 
               imageRef = "images/kent_hardAtWorkOnMac.jpg";
            }else{
               imageRef = "images/kent_hardAtWorkOnWin.jpg";
            }
         }else{
            imageRef = "images/kent_sleeping.jpg";
         }
      //If it's after midnight and before 10am, or anytime on Sunday
      }else{
         imageRef = "images/kent_sleeping.jpg";
      }
      
      return imageRef;
    }
    
    </script>
    </head>
    
    <body>
    </body>
    </html>
    
  3. Enregistrez le fichier sous le nom kent.htm dans le dossier Configuration/Translators.