Precompile template
347521
function precompile(tmpl, outputH, tmplRule) {
  var root = _createAstRoot();

  if (tmpl.quasis) {
    var _tmpl = tmpl,
        quasis = _tmpl.quasis,
        isExpression = _tmpl.isExpression,
        isCss = _tmpl.isCss;
    tmpl = compileStringTmpl.call({
      tmplRule: tmplRule,
      outputH: outputH,
      onlyParse: true,
      isExpression: isExpression,
      isCss: isCss
    }, quasis);
  } else if (isString(tmpl)) {
    tmpl = compileStringTmpl.call({
      tmplRule: tmplRule,
      outputH: outputH,
      onlyParse: true
    }, tmpl);
  }

  checkElem(tmpl._njTmpl, root, tmplRule);
  return buildRuntime(root.content, root, !outputH);
}
400136
function compile (template, data) {
    for (var name in data) {
      template = template.replace('{{' + name + '}}', data[name])
    }
    return template
  }
1371846
function compileTemplates() {
  const mainHtml = fs.readFileSync(path.resolve(docsDir, 'src/template.html'), {
    encoding: 'utf8',
  });
  const mainTemplate = Handlebars.compile(mainHtml);

  function createPage(fileName, tab, content) {
    const html = mainTemplate({
      tabs: [{
        title: 'Get started',
        url: 'get-started.html',
        selected: tab === 'get-started',
      }, {
        title: 'Components',
        url: 'components.html',
        selected: tab === 'components',
      }],
      content,
      luiVersion: LUI_VERSION,
    });
    fileUtil.writeFile(path.resolve(docsDir, 'dist', fileName), html);
  }

  function createIndexPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/index.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template();
    return createPage('index.html', 'index', html);
  }

  function createGetStartedPage() {
    const content = fs.readFileSync(path.resolve(docsDir, 'src/pages/get-started.html'), {
      encoding: 'utf8',
    });
    const template = Handlebars.compile(content);
    const html = template({
      luiVersion: LUI_VERSION,
    });
    return createPage('get-started.html', 'get-started', html);
  }

  function createComponentPage(templateName, template, tab, content) {
    return createPage(templateName, tab, template({
      content,
      sections: sections.map(section => ({
        name: section.name,
        pages: section.pages.map(page => ({
          name: page.name,
          template: page.template,
          selected: page.template === templateName,
        })),
      })),
    }));
  }

  function createComponentPages() {
    const componentHtml = fs.readFileSync(path.resolve(docsDir, 'src/component-template.html'), {
      encoding: 'utf8',
    });
    const componentTemplate = Handlebars.compile(componentHtml);

    sections.forEach((section) => {
      section.pages.forEach((page) => {
        const file = `src/pages/${page.template}`;
        const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
          encoding: 'utf8',
        });

        const template = Handlebars.compile(fileContent);
        const html = template();

        createComponentPage(page.template, componentTemplate, 'components', html);
      });
    });

    const file = 'src/pages/components.html';
    const fileContent = fs.readFileSync(path.resolve(docsDir, file), {
      encoding: 'utf8',
    });
    createComponentPage('components.html', componentTemplate, 'components', fileContent);
  }

  createIndexPage();
  createGetStartedPage();
  createComponentPages();
}
43389
public function compile(Core $core, ITemplate $template)
    {
        // init vars
        //		$compiled = '';
        $tpl                  = $template->getSource();
        $ptr                  = 0;
        $this->core           = $core;
        $this->template       = $template;
        $this->templateSource = &$tpl;
        $this->pointer        = &$ptr;

        while (true) {
            // if pointer is at the beginning, reset everything, that allows a plugin to externally reset the compiler if everything must be reparsed
            if ($ptr === 0) {
                // resets variables
                $this->usedPlugins     = array();
                $this->data            = array();
                $this->scope           = &$this->data;
                $this->scopeTree       = array();
                $this->stack           = array();
                $this->line            = 1;
                $this->templatePlugins = array();
                // add top level block
                $compiled                 = $this->addBlock('TopLevelBlock', array(), 0);
                $this->stack[0]['buffer'] = '';

                if ($this->debug) {
                    echo "\n";
                    echo 'COMPILER INIT' . "\n";
                }

                if ($this->debug) {
                    echo 'PROCESSING PREPROCESSORS (' . count($this->processors['pre']) . ')' . "\n";
                }

                // runs preprocessors
                foreach ($this->processors['pre'] as $preProc) {
                    if (is_array($preProc) && isset($preProc['autoload'])) {
                        $preProc = $this->loadProcessor($preProc['class'], $preProc['name']);
                    }
                    if (is_array($preProc) && $preProc[0] instanceof Processor) {
                        $tpl = call_user_func($preProc, $tpl);
                    } else {
                        $tpl = call_user_func($preProc, $this, $tpl);
                    }
                }
                unset($preProc);

                // show template source if debug
                if ($this->debug) {
                    echo '<pre>'.print_r(htmlentities($tpl), true).'</pre>'."\n";
                }

                // strips php tags if required by the security policy
                if ($this->securityPolicy !== null) {
                    $search = array('{<\?php.*?\?>}');
                    if (ini_get('short_open_tags')) {
                        $search = array('{<\?.*?\?>}', '{<%.*?%>}');
                    }
                    switch ($this->securityPolicy->getPhpHandling()) {
                        case SecurityPolicy::PHP_ALLOW:
                            break;
                        case SecurityPolicy::PHP_ENCODE:
                            $tpl = preg_replace_callback($search, array($this, 'phpTagEncodingHelper'), $tpl);
                            break;
                        case SecurityPolicy::PHP_REMOVE:
                            $tpl = preg_replace($search, '', $tpl);
                    }
                }
            }

            $pos = strpos($tpl, $this->ld, $ptr);

            if ($pos === false) {
                $this->push(substr($tpl, $ptr), 0);
                break;
            } elseif (substr($tpl, $pos - 1, 1) === '\\' && substr($tpl, $pos - 2, 1) !== '\\') {
                $this->push(substr($tpl, $ptr, $pos - $ptr - 1) . $this->ld);
                $ptr = $pos + strlen($this->ld);
            } elseif (preg_match('/^' . $this->ldr . ($this->allowLooseOpenings ? '\s*' : '') . 'literal' . ($this->allowLooseOpenings ? '\s*' : '') . $this->rdr . '/s', substr($tpl, $pos), $litOpen)) {
                if (!preg_match('/' . $this->ldr . ($this->allowLooseOpenings ? '\s*' : '') . '\/literal' . ($this->allowLooseOpenings ? '\s*' : '') . $this->rdr . '/s', $tpl, $litClose, PREG_OFFSET_CAPTURE, $pos)) {
                    throw new CompilationException($this, 'The {literal} blocks must be closed explicitly with {/literal}');
                }
                $endpos = $litClose[0][1];
                $this->push(substr($tpl, $ptr, $pos - $ptr) . substr($tpl, $pos + strlen($litOpen[0]), $endpos - $pos - strlen($litOpen[0])));
                $ptr = $endpos + strlen($litClose[0][0]);
            } else {
                if (substr($tpl, $pos - 2, 1) === '\\' && substr($tpl, $pos - 1, 1) === '\\') {
                    $this->push(substr($tpl, $ptr, $pos - $ptr - 1));
                    $ptr = $pos;
                }

                $this->push(substr($tpl, $ptr, $pos - $ptr));
                $ptr = $pos;

                $pos += strlen($this->ld);
                if ($this->allowLooseOpenings) {
                    while (substr($tpl, $pos, 1) === ' ') {
                        $pos += 1;
                    }
                } else {
                    if (substr($tpl, $pos, 1) === ' ' || substr($tpl, $pos, 1) === "\r" || substr($tpl, $pos, 1) === "\n" || substr($tpl, $pos, 1) === "\t") {
                        $ptr = $pos;
                        $this->push($this->ld);
                        continue;
                    }
                }

                // check that there is an end tag present
                if (strpos($tpl, $this->rd, $pos) === false) {
                    throw new CompilationException($this, 'A template tag was not closed, started with "' . substr($tpl, $ptr, 30) . '"');
                }

                $ptr += strlen($this->ld);
                $subptr = $ptr;

                while (true) {
                    $parsed = $this->parse($tpl, $subptr, null, false, 'root', $subptr);

                    // reload loop if the compiler was reset
                    if ($ptr === 0) {
                        continue 2;
                    }

                    $len = $subptr - $ptr;
                    $this->push($parsed, substr_count(substr($tpl, $ptr, $len), "\n"));
                    $ptr += $len;

                    if ($parsed === false) {
                        break;
                    }
                }
            }
        }

        $compiled .= $this->removeBlock('TopLevelBlock');

        if ($this->debug) {
            echo 'PROCESSING POSTPROCESSORS' . "\n";
        }

        foreach ($this->processors['post'] as $postProc) {
            if (is_array($postProc) && isset($postProc['autoload'])) {
                $postProc = $this->loadProcessor($postProc['class'], $postProc['name']);
            }
            if (is_array($postProc) && $postProc[0] instanceof Processor) {
                $compiled = call_user_func($postProc, $compiled);
            } else {
                $compiled = call_user_func($postProc, $this, $compiled);
            }
        }
        unset($postProc);

        if ($this->debug) {
            echo 'COMPILATION COMPLETE : MEM USAGE : ' . memory_get_usage() . "\n";
        }

        $output = "<?php\n/* template head */\n";

        // build plugin preloader
        foreach ($this->getUsedPlugins() as $plugin => $type) {
            if ($type & Core::CUSTOM_PLUGIN) {
                continue;
            }

            switch ($type) {
                case Core::CLASS_PLUGIN:
                case Core::CLASS_PLUGIN + Core::BLOCK_PLUGIN:
                    if (class_exists('Plugin' . $plugin) !== false) {
                        $output .= "if (class_exists('" . "Plugin" . $plugin . "')===false)".
                        "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    } else {
                        $output .= "if (class_exists('" . Core::NAMESPACE_PLUGINS_BLOCKS . "Plugin" . $plugin . "')===false)".
                        "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    }
                    break;
                case Core::CLASS_PLUGIN + Core::FUNC_PLUGIN:
                    if (class_exists('Plugin' . $plugin) !== false) {
                        $output .= "if (class_exists('" . "Plugin" . $plugin . "')===false)".
                            "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    } else {
                        $output .= "if (class_exists('" . Core::NAMESPACE_PLUGINS_FUNCTIONS . "Plugin" . $plugin . "')===false)".
                            "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    }
                    break;
                case Core::FUNC_PLUGIN:
                    if (function_exists('Plugin' . $plugin) !== false) {
                        $output .= "if (function_exists('" . "Plugin" . $plugin . "')===false)".
                        "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    } else {
                        $output .= "if (function_exists('" . Core::NAMESPACE_PLUGINS_FUNCTIONS . "Plugin" . $plugin . "')===false)".
                        "\n\t\$this->getLoader()->loadPlugin('Plugin$plugin');\n";
                    }
                    break;
                case Core::SMARTY_MODIFIER:
                    $output .= "if (function_exists('smarty_modifier_$plugin')===false)".
                    "\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
                    break;
                case Core::SMARTY_FUNCTION:
                    $output .= "if (function_exists('smarty_function_$plugin')===false)".
                    "\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
                    break;
                case Core::SMARTY_BLOCK:
                    $output .= "if (function_exists('smarty_block_$plugin')===false)".
                    "\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
                    break;
                case Core::PROXY_PLUGIN:
                    $output .= $this->getCore()->getPluginProxy()->getLoader($plugin);
                    break;
                default:
                    throw new CompilationException($this, 'Type error for ' . $plugin . ' with type' . $type);
            }
        }

        foreach ($this->templatePlugins as $function => $attr) {
            if (isset($attr['called']) && $attr['called'] === true && !isset($attr['checked'])) {
                $this->resolveSubTemplateDependencies($function);
            }
        }
        foreach ($this->templatePlugins as $function) {
            if (isset($function['called']) && $function['called'] === true) {
                $output .= $function['body'] . PHP_EOL;
            }
        }

        $output .= $compiled . "\n?>";

        $output = preg_replace('/(?<!;|\}|\*\/|\n|\{)(\s*' . preg_quote(self::PHP_CLOSE, '/') . preg_quote(self::PHP_OPEN, '/') . ')/', ";\n", $output);
        $output = str_replace(self::PHP_CLOSE . self::PHP_OPEN, "\n", $output);

        // handle <?xml tag at the beginning
        $output = preg_replace('#(/\* template body \*/ \?>\s*)<\?xml#is', '$1<?php echo \'<?xml\'; ?>', $output);

        // add another line break after PHP closing tags that have a line break following,
        // as we do not know whether it's intended, and PHP will strip it otherwise
        $output = preg_replace('/(?<!"|<\?xml)\s*\?>\n/', '$0' . "\n", $output);

        if ($this->debug) {
            echo '=============================================================================================' . "\n";
            $lines = preg_split('{\r\n|\n|<br />}', $output);
            array_shift($lines);
            foreach ($lines as $i => $line) {
                echo ($i + 1) . '. ' . $line . "\r\n";
            }
            echo '=============================================================================================' . "\n";
        }

        $this->template = $this->dwoo = null;
        $tpl            = null;

        return $output;
    }
349956
function compileTemplate () {
    var template = $attrs.$mdTabsTemplate,
        element  = angular.element($element[0].querySelector('md-tab-data'));

    element.html(template);
    $compile(element.contents())(ctrl.parent);
    delete $attrs.$mdTabsTemplate;
  }
558279
function precompile({ code, files }) {
    return resolve(files)
        .then(filter(test(/^locales(\/|\\)[a-z]{2,3}(_[A-Z]{2})?\.json$/)))
        .then(localesToPairs)
        .then(runInAllLocales(code))
        .then(createMetaFile)
        .return(['.meta', ...files]);
}
1314537
function setupTemplates() {
  
  // Reset templates before proceeding
  // NOTE: This is needed for templates to be copatible with hot code loading
  this.templates = {};

  var self = this;
  var tplDir = app.mvcpath + app.paths.templates;
  var multiSlashes = this.regex.multipleSlashes;
  
  if (fs.existsSync(tplDir) && fs.statSync(tplDir).isDirectory()) {
    
    var files = protos.util.walkDir(tplDir, this.regex.templateFile);
  
    files.forEach(function(path) {
      buildTemplatePartial.call(this, path);
      watchPartial.call(this, path, buildTemplatePartial);
    }, this);
    
  }
  
  this.emit('templates_loaded', this.templates);
  
}
87452
def generate_template(template_name, **context):
    """"""
    context.update(href=href, format_datetime=format_datetime)
    return template_loader.load(template_name).generate(**context)
353313
@Deprecated
    public static PredicateTemplate predicateTemplate(String template, ImmutableList<?> args) {
        return predicateTemplate(TemplateFactory.DEFAULT.create(template), args);
    }
1235107
public static PredicateTemplate predicateTemplate(String template, Object... args) {
        return predicateTemplate(TemplateFactory.DEFAULT.create(template), ImmutableList.copyOf(args));
    }
491529
def template(*args, **kwargs):
    '''
    
    '''
    tpl = args[0] if args else None
    template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
    if tpl not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
        if isinstance(tpl, template_adapter):
            TEMPLATES[tpl] = tpl
            if settings: TEMPLATES[tpl].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tpl]:
        abort(500, 'Template (%s) not found' % tpl)
    for dictarg in args[1:]: kwargs.update(dictarg)
    return TEMPLATES[tpl].render(kwargs)
962543
function compile(templates) {
    templates.forEach(partial => {
      partials[partial.name] = Handlebars.compile(partial.source);
      Handlebars.registerPartial(partial.name, partials[partial.name]);
    });
  }
986563
function() {
  gulp.task('tpl-precompile', function() {
    return gulp.src([paths.src.partials])
    .pipe($.htmlmin({
      removeComments: true,
      collapseWhitespace: plugins.tpls.ext === '.jade' ? false : true
    }))
    .pipe(plugins.tpls.cmd(plugins.tpls.config))
    .on('error', handleError)
    .pipe($.defineModule('plain'))
    .pipe($.declare({
      namespace: 'R.templates',
      processName: function(file) {
        var dir = config.paths.src.partials || config.paths.src.templates;
        return file.slice(file.indexOf(dir) + dir.length).replace('.js', '');
      }
    }))
    .pipe($.concat('templates.js'))
    .pipe(gulp.dest(paths.out.js));
  });

  /* Template livereloading  */
  gulp.task('tpl-reload', ['tpl-precompile'], function() {
    return gulp.src([paths.src.views])
    .pipe($.livereload(lrport));
  });
}
122882
public function compile(): void
	{
		// Get teplate contents

		$contents = $this->fileSystem->get($this->template);

		// Compile template

		foreach($this->compileOrder as $method)
		{
			$contents = $this->$method($contents);
		}

		// Store compiled template

		$this->fileSystem->put($this->cachePath . '/' . md5($this->template) . '.php', trim($contents));
	}
4405
function prepareTemplates(templates){
  var valueGeneratorsDict = {
    select: function(obj){
      var types = {
        random:function(){
          return obj.choice[Math.floor(Math.random() * obj.choice.length)];
        },
        liner: function(){
          var el = obj.choice.shift();
          obj.choice.push(el);
          return el;
        },
        random_unique: function(){
          function shuffle(o) {
            for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
            return o;
          };
          if(!obj.randomized){obj.randomized = shuffle(obj.choice.slice());}
          var el = obj.randomized.shift();
          if(el===undefined){
            log.notEnoughChoice('random_unique','choice');
            process.exit()
          }
          return el;
        }
      }
      if(!types[obj.type]){
        return log.noTemplateType('select', obj.type, Object.keys(types))
      }
      return types[obj.type]
    },
    lipsum: function(obj){
      if(!(obj.max_char_length&&obj.min_char_length)){
        return log.missingSettings('lipsum', '', ['max_char_length','mim_char_length'])
      }
      var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
      return function(){
        var chars = Math.floor(Math.random()*(obj.max_char_length-obj.min_char_length)+obj.min_char_length)
        var str = lorem.slice(0, chars)
        while(str.length < chars){
          var len = chars - str.length
          str += ' '+lorem.slice(0, len)
        }
        return str
      }
    },
    number: function(obj){
      var types = {
        random:function(){
          return Math.floor(Math.random()*(obj.max_num-obj.min_num)+obj.min_num);
        },
        incremental: function(){
          tempdata += obj.increments
          return tempdata;
        }
      }

      if(!types[obj.type]){
        return log.noTemplateType('number', obj.type, Object.keys(types))
      }
      if(obj.type == 'random' && !(obj.max_num&&obj.min_num)){
        return log.missingSettings('number', 'random', ['max_num','min_num'])
      }
      if(obj.type == 'incremental'){
        if(!(obj.starting_num&&obj.increments)){
          return log.missingSettings('number', 'incremental', ['starting_num','increments'])
        }
        var tempdata = this[obj.id] = obj.starting_num - obj.increments
      }

      return types[obj.type]
    },
    datetime: function(obj){
      var types = {
        random:function(){
          return output[obj.output_format](new Date(Math.floor(Math.random()*(max-min)+min)));
        },
        incremental: function(){
          tempdata += obj.increments
          return output[obj.output_format](new Date(tempdata));
        }
      }
      var output = {
        toString: function(d){ return d.toString(); },
        toDateString: function(d){ return d.toDateString(); },
        toISOString: function(d){ return d.toISOString(); },
        toJSON: function(d){ return d.toJSON(); },
        toGMTString: function(d){ return d.toGMTString(); },
        toLocaleDateString: function(d){ return d.toLocaleDateString(); },
        toLocaleString: function(d){ return d.toLocaleString(); },
        toLocaleTimeString: function(d){ return d.toLocaleTimeString(); },
        toTimeString: function(d){ return d.toTimeString(); },
        toUTCString: function(d){ return d.toUTCString(); },
        toYMDString:function(d){
          return d.toJSON().split('T')[0]
        }
      }

      if(!types[obj.type]){
        return log.noTemplateType('date', obj.type, Object.keys(types))
      }
      if(obj.type == 'random'){
        if(!(obj.max_datetime&&obj.min_datetime&&obj.output_format)){
          return log.missingSettings('date', 'random', ['max_datetime','min_datetime','output_format'])
        }
        var min = Date.parse(obj.min_datetime)
        var max = Date.parse(obj.max_datetime)
        if(isNaN(min)){
          return log.notParseableDatetime('min_datetime', obj.min_datetime)
        }else if(isNaN(max)){
          return log.notParseableDatetime('max_datetime', obj.max_datetime)
        }
      }
      if(obj.type == 'incremental'){
        if(!(obj.starting_datetime&&obj.increments&&obj.output_format)){
          return log.missingSettings('number', 'incremental', ['starting_datetime','increments','output_format'])
        }
        var tempdata = this[obj.id] = Date.parse(obj.starting_datetime) - obj.increments
        if(isNaN(tempdata)){
          return log.notParseableDatetime('starting_datetime', obj.starting_datetime)
        }
      }

      return types[obj.type]
    }
  }

  /*
  Recursively iterate each key in template object to find `stub_type` key.
  If the object has `stub_type` key, replace itself with corresponding
  function in valueGenerators valid
  Arg:
    - obj (Object)
  */
  function parseTemplate(obj) {
    for (var key in obj) {
      if (obj[key] !== null && typeof(obj[key])=="object") {
        if(obj[key].stub_type){
          if(!valueGeneratorsDict[obj[key].stub_type]){
            log.stubTypeNotFound(obj[key].stub_type)
          }else{
            obj[key].id = crypto.randomBytes(16).toString('hex');
            obj[key] = valueGeneratorsDict[obj[key].stub_type](obj[key])
          }
        }else{
          parseTemplate(obj[key]);
        }
      }
    }
  }

  if(templates){
    Object.keys(templates).map(function(t){
      parseTemplate(templates[t]);
    })
    return templates;
  }else{
    return [];
  }
}
96644
public static PredicateTemplate predicateTemplate(String template, List<?> args) {
        return predicateTemplate(TemplateFactory.DEFAULT.create(template), args);
    }
244237
static function compileTemplate( $tpl, $key, &$resourceData )
    {
        if ( !eZTemplateCompiler::isCompilationEnabled() )
            return false;

        $resourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();

        $cacheFileName = eZTemplateCompiler::compilationFilename( $key, $resourceData );
        $resourceData['uniqid'] = md5( $resourceData['template-filename']. uniqid( "ezp". getmypid(), true ) );

        // Time limit #1:
        // We reset the time limit to 30 seconds to ensure that templates
        // have enough time to compile
        // However if time limit is unlimited (0) we leave it be
        // Time limit will also be reset after subtemplates are compiled
        $maxExecutionTime = ini_get( 'max_execution_time' );
        if ( $maxExecutionTime != 0 && $maxExecutionTime < 30 )
        {
            @set_time_limit( 30 );
        }

        $rootNode =& $resourceData['root-node'];
        if ( !$rootNode )
            return false;

        $GLOBALS['eZTemplateCompilerResourceCache'][$resourceData['template-filename']] =& $resourceData;

        $useComments = eZTemplateCompiler::isCommentsEnabled();

        if ( !$resourceData['test-compile'] )
        {
            eZTemplateCompiler::createCommonCompileTemplate();
        }

        /* Check if we need to disable the generation of spacing for the compiled templates */
        $ini = eZINI::instance();
        $spacing = 'disabled';
        if ( $ini->variable( 'TemplateSettings', 'UseFormatting' ) == 'enabled' )
        {
            $spacing = 'enabled';
        }

        $php = new eZPHPCreator( eZTemplateCompiler::compilationDirectory(), $cacheFileName,
                                 eZTemplateCompiler::TemplatePrefix(), array( 'spacing' => $spacing ) );
        $php->addComment( 'URI:       ' . $resourceData['uri'] );
        $php->addComment( 'Filename:  ' . $resourceData['template-filename'] );
        $php->addComment( 'Timestamp: ' . $resourceData['time-stamp'] . ' (' . date( 'D M j G:i:s T Y', $resourceData['time-stamp'] ) . ')' );

        $php->addCodePiece("\$oldSetArray_{$resourceData['uniqid']} = isset( \$setArray ) ? \$setArray : array();\n".
                           "\$setArray = array();\n");
// Code to decrement include level of the templates
        $php->addCodePiece( "\$tpl->Level++;\n" );
        $php->addCodePiece( "if ( \$tpl->Level > $tpl->MaxLevel )\n".
                            "{\n".
                            "\$text = \$tpl->MaxLevelWarning;".
                            "\$tpl->Level--;\n".
                            "return;\n".
                            "}\n" );
        if ( $resourceData['locales'] && count( $resourceData['locales'] ) )
        {
            $php->addComment( 'Locales:   ' . join( ', ', $resourceData['locales'] ) );

            $php->addCodePiece(
                '$locales = array( "'. join( '", "', $resourceData['locales'] ) . "\" );\n".
                '$oldLocale_'. $resourceData['uniqid']. ' = setlocale( LC_CTYPE, null );'. "\n".
                '$currentLocale_'. $resourceData['uniqid']. ' = setlocale( LC_CTYPE, $locales );'. "\n"
            );
        }
//         $php->addCodePiece( "print( \"" . $resourceData['template-filename'] . " ($cacheFileName)<br/>\n\" );" );
        if ( $useComments )
        {
            $templateFilename = $resourceData['template-filename'];
            if ( file_exists( $templateFilename ) )
            {
                $fd = fopen( $templateFilename, 'rb' );
                if ( $fd )
                {
                    $templateText = fread( $fd, filesize( $templateFilename ) );
                    $php->addComment( "Original code:\n" . $templateText );
                    fclose( $fd );
                }
            }
        }
        $php->addVariable( 'eZTemplateCompilerCodeDate', eZTemplateCompiler::CODE_DATE );
        $php->addCodePiece( "if ( !defined( 'EZ_TEMPLATE_COMPILER_COMMON_CODE' ) )\n" );
        $php->addInclude( eZTemplateCompiler::compilationDirectory() . '/common.php', eZPHPCreator::INCLUDE_ONCE_STATEMENT, array( 'spacing' => 4 ) );
        $php->addSpace();

        if ( eZTemplateCompiler::isAccumulatorsEnabled() )
        {
            $php->addCodePiece( "eZDebug::accumulatorStart( 'template_compiled_execution', 'template_total', 'Template compiled execution', true );\n" );
        }
        if ( eZTemplateCompiler::isTimingPointsEnabled() )
        {
            $php->addCodePiece( "eZDebug::addTimingPoint( 'Script start $cacheFileName' );\n" );
        }

//         $php->addCodePiece( "if ( !isset( \$vars ) )\n    \$vars =& \$tpl->Variables;\n" );
//         $php->addSpace();

        $parameters = array();
        $textName = eZTemplateCompiler::currentTextName( $parameters );

//         $php->addCodePiece( "if ( !isset( \$$textName ) )\n    \$$textName = '';\n" );
//         $php->addSpace();

        $transformedTree = array();
        eZTemplateCompiler::processNodeTransformation( $useComments, $php, $tpl, $rootNode, $resourceData, $transformedTree );

        if ( $ini->variable( 'TemplateSettings', 'TemplateOptimization' ) == 'enabled' )
        {
            /* Retrieve class information for the attribute lookup table */
            if ( isset( $resourceData['handler']->Keys ) and isset( $resourceData['handler']->Keys['class'] ) ) {
                $resourceData['class-info'] = eZTemplateOptimizer::fetchClassDeclaration( $resourceData['handler']->Keys['class'] );
            }
            /* Run the optimizations */
            eZTemplateOptimizer::optimize( $useComments, $php, $tpl, $transformedTree, $resourceData );
        }

        $staticTree = array();
        eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl, $transformedTree, $resourceData, $staticTree );

        $combinedTree = array();
        eZTemplateCompiler::processNodeCombining( $useComments, $php, $tpl, $staticTree, $resourceData, $combinedTree );

        $finalTree = $combinedTree;
        if ( !eZTemplateCompiler::isNodePlacementEnabled() )
            eZTemplateCompiler::processRemoveNodePlacement( $finalTree );

        eZTemplateCompiler::generatePHPCode( $useComments, $php, $tpl, $finalTree, $resourceData );

        if ( eZTemplateCompiler::isTreeEnabled( 'final' ) )
            $php->addVariable( 'finalTree', $finalTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'combined' ) )
            $php->addVariable( 'combinedTree', $combinedTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'static' ) )
            $php->addVariable( 'staticTree', $staticTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'transformed' ) )
            $php->addVariable( 'transformedTree', $transformedTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'original' ) )
            $php->addVariable( 'originalTree', $rootNode, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );

        if ( eZTemplateCompiler::isTimingPointsEnabled() )
            $php->addCodePiece( "eZDebug::addTimingPoint( 'Script end $cacheFileName' );\n" );
        if ( eZTemplateCompiler::isAccumulatorsEnabled() )
            $php->addCodePiece( "eZDebug::accumulatorStop( 'template_compiled_execution', true );\n" );

        if ( $resourceData['locales'] && count( $resourceData['locales'] ) )
        {
            $php->addCodePiece(
                'setlocale( LC_CTYPE, $oldLocale_'. $resourceData['uniqid']. ' );'. "\n"
            );
        }
        $php->addCodePiece('$setArray = $oldSetArray_'. $resourceData['uniqid']. ";\n");

// Code to decrement include level of the templates
        $php->addCodePiece("\$tpl->Level--;\n" );

        /*
        // dump names of all defined PHP variables
        $php->addCodePiece( "echo \"defined vars in $resourceData[uri]:<br/><pre>\\n\";\n" );
        $php->addCodePiece( 'foreach ( array_keys( get_defined_vars() ) as $var_name  ) echo "- $var_name\n";' );
        // dump tpl vars
        $php->addCodePiece( 'echo "\n-----------------------------------------------------------\nvars: ";' );
        $php->addCodePiece( 'var_dump( $vars );' );
        $php->addCodePiece( 'echo "</pre><hr/>\n";' );
        */

        if ( !$resourceData['test-compile'] )
        {
            $php->store( true );
        }

        return true;
    }