includes/clientside/static/template-compiler.js
author Dan
Sun, 04 May 2008 21:57:48 -0400
changeset 541 acb7e23b6ffa
parent 212 30b857a6b811
child 582 a38876c0793c
permissions -rw-r--r--
Massive commit with various changes. Added user ranks system (no admin interface yet) and ability for users to have custom user titles. Made cron framework accept fractions of hours through floating-point intervals. Modifed ACL editor to use miniPrompt framework for close confirmation box. Made avatar system use a special page as opposed to fetching the files directly for caching reasons.

// An implementation of Enano's template compiler in Javascript. Same exact API
// as the PHP version - constructor accepts text, then the assign_vars, assign_bool, and run methods.

function templateParser(text)
{
  this.tpl_code    = text;
  this.tpl_strings = new Object();
  this.tpl_bool    = new Object();
  this.assign_vars = __tpAssignVars;
  this.assign_bool = __tpAssignBool;
  this.run         = __tpRun;
}

function __tpAssignVars(vars)
{
  for(var i in vars)
  {
    this.tpl_strings[i] = vars[i];
  }
}

function __tpAssignBool(vars)
{
  for(var i in vars)
  {
    this.tpl_bool[i] = ( vars[i] ) ? true : false; 
  }
}

function __tpRun()
{
  if(typeof(this.tpl_code) == 'string')
  {
    tpl_code = __tpCompileTemplate(this.tpl_code);
    try {
      compiled = eval(tpl_code);
    }
    catch(e)
    {
      alert(e);
      aclDebug(tpl_code);
    }
    return compiled;
  }
  return false;
}

function __tpCompileTemplate(code)
{
  // Compile plaintext/template code to javascript code
  code = code.replace(/\\/g, "\\\\");
  code = code.replace(/\'/g,  "\\'");
  code = code.replace(/\"/g,  '\\"');
  code = code.replace(new RegExp(unescape('%0A'), 'g'), '\\n');
  code = "'" + code + "'";
  code = code.replace(/\{([A-z0-9_-]+)\}/ig, "' + this.tpl_strings['$1'] + '");
  code = code.replace(/\{lang:([a-z0-9_]+)\}/g, "' + $lang.get('$1') + '");
  code = code.replace(/\<!-- BEGIN ([A-z0-9_-]+) --\>([\s\S]*?)\<!-- BEGINELSE \1 --\>([\s\S]*?)\<!-- END \1 --\>/ig, "' + ( ( this.tpl_bool['$1'] == true ) ? '$2' : '$3' ) + '");
  code = code.replace(/\<!-- BEGIN ([A-z0-9_-]+) --\>([\s\S]*?)\<!-- END \1 --\>/ig, "' + ( ( this.tpl_bool['$1'] == true ) ? '$2' : '' ) + '");
  return code;
}

function __tpExtractVars(code)
{
  code = code.replace('\\', "\\\\");
  code = code.replace("'",  "\\'");
  code = code.replace('"',  '\\"');
  code = code.replace(new RegExp(unescape('%0A'), 'g'), "\\n");
  code = code.match(/\<!-- VAR ([A-z0-9_-]+) --\>([\s\S]*?)\<!-- ENDVAR \1 -->/g);
  code2 = '';
  for(var i in code)
    if(typeof(code[i]) == 'string')
      code2 = code2 + code[i];
  code = code2.replace(/\<!-- VAR ([A-z0-9_-]+) --\>([\s\S]*?)\<!-- ENDVAR \1 -->/g, "'$1' : \"$2\",");
  code = '( { ' + code + ' "________null________" : false } )';
  vars = eval(code);
  return vars;
}