LightnCandy Documentation

repository·master·Indexed 20 days ago

https://github.com/zordius/lightncandy

A high-performance PHP implementation of Handlebars and Mustache template engines. LightnCandy compiles templates into pure PHP code that can run standalone. It features extensive compatibility flags for JavaScript and Mustache specifications, support for custom block and expression helpers, configurable template delimiters, and a comprehensive debugging system via the LightnCandy\Runtime class.

Tokens
5K
Snippets
20
Records
28
Agent score
70%

What's inside LightnCandy

  1. Debug templates and find missing data

    master

    To debug templates, compile with FLAG_RENDER_DEBUG. This generates a template containing extra debug information. When rendering, pass one of the LightnCandy\Runtime debug constants to the render function to see errors or visual tags.

    Render Debug Options

    • DEBUG_ERROR_LOG: Call error_log() when data is missing.
    • DEBUG_ERROR_EXCEPTION: Throw an exception when data is missing.
    • DEBUG_TAGS: Return normalized Mustache tags.
    • DEBUG_TAGS_ANSI: Return normalized Mustache tags with ANSI color.
    • DEBUG_TAGS_HTML: Return normalized Mustache tags with HTML comments.

    Usage Example

    // 1. Compile with debug flag
    $phpStr = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_RENDER_DEBUG | LightnCandy::FLAG_HANDLEBARSJS
    ));
    
    // 2. Save and include the compiled PHP
    file_put_contents('render.php', '<?php ' . $phpStr . '?>');
    $renderer = include('render.php');
    
    // 3. Render with a debug mode
    $renderer(array('name' => 'John'), array('debug' => LightnCandy\Runtime::DEBUG_ERROR_LOG));
    $phpStr = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_RENDER_DEBUG | LightnCandy::FLAG_HANDLEBARSJS
    ));
    
    file_put_contents('render.php', '<?php ' . $phpStr . '?>');
    $renderer = include('render.php');
    
    $renderer(array('name' => 'John'), array('debug' => LightnCandy\Runtime::DEBUG_ERROR_LOG));
  2. Handle template recompilation during upgrades

    master

    When upgrading LightnCandy, follow these rules regarding template execution:

    • Standalone templates: Templates compiled by older versions of LightnCandy remain safe and can be executed without changes when upgrading to a new version.
    • Non-standalone templates: You must recompile all non-standalone templates whenever you upgrade LightnCandy to ensure compatibility with the current runtime.
  3. Configure error handling via compiler flags

    master

    You can control how LightnCandy handles errors by passing specific flags in the $options array during compilation.

    When errors are detected in the context:

    • If 'flags' => ['errorlog' => 1] is set, errors are sent to the PHP error_log().
    • If 'flags' => ['exception' => 1] is set, an \Exception is thrown containing the error messages.

    Note: If neither flag is set, compile() will simply return false.

  4. Avoid 'Class not found' errors when upgrading from v0.12 or v0.11

    master

    Due to changes in the render() debugging implementation, the rendering supporting class was renamed from LCRun2 to LCRun3 in version v0.12.

    Action Required: If you compiled templates as non-standalone PHP code using LightnCandy v0.11 or earlier, you must recompile them to avoid a Class 'LCRun2' not found error.

  5. Customize the rendering runtime class

    master

    You can replace the default LightnCandy\Runtime with your own implementation by providing the class name in the runtime option during compilation.

    class MyRunTime extends LightnCandy\Runtime {
        public static function raw($cx, $v) {
            return '[[DEBUG:raw()=>' . var_export($v, true) . ']]';
        }
    }
    
    $php = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_HANDLEBARSJS,
        'runtime' => 'MyRunTime'
    ));

    Note: The class must exist during both compilation and rendering (especially if using FLAG_STANDALONEPHP).

  6. Customize the render function with `renderex`

    master

    The renderex option allows you to inject custom PHP code into the generated render function. This code is executed inside the render function scope.

    $php = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_HANDLEBARSJS,
        'renderex' => '// Compiled at ' . date('Y-m-d h:i:s')
    ));

    Note: Ensure the passed string is valid PHP; LightnCandy does not validate it.

  7. Implement custom helpers in LightnCandy

    master

    Register custom helpers by passing an associative array to the helpers key in the compile() options. Helpers receive $context and an $options array.

    Block Helper Example (#mywith) To implement a block helper that changes context (similar to {{#with}}):

    $php = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_HANDLEBARSJS,
        'helpers' => array(
            'mywith' => function ($context, $options) {
                return $options['fn']($context);
            }
        )
    ));

    Helper Metadata

    • Use isset($options['fn']) to detect if the helper is a block helper.
    • Use isset($options['inverse']) to detect the existence of an {{else}} block.
    • Access special data via $options['data'] (e.g., $options['data']['root'] for {{@root}}).
    • Access current context via $options['_this'].
  8. Change template delimiters

    master

    You can change the default {{ and }} delimiters using the delimiters option in compile(). This applies to the template and all included partials.

    LightnCandy::compile('I wanna use <% foo %> as delimiters!', array(
        'delimiters' => array('<%', '%>')
    ));
  9. Preprocess partials during compilation

    master

    Use the prepartial option in compile() to run a callback before a partial is compiled. This is useful for injecting metadata or modifying the partial content.

    $php = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_HANDLEBARSJS,
        'prepartial' => function ($context, $template, $name) {
            return "<!-- partial start: $name -->$template<!-- partial end: $name -->";
        }
    ));
  10. Compile templates with LightnCandy::compile()

    master

    Use LightnCandy::compile($template, $options) to transform a Handlebars or Mustache template into pure PHP code. By default, it compiles to high-performance PHP. You can pass an array of flags to customize behavior, such as error handling or compatibility modes.

    $php = LightnCandy::compile($template, array(
        'flags' => LightnCandy::FLAG_ERROR_LOG | LightnCandy::FLAG_STANDALONEPHP
    ));