Liquid template engine for PHP

Overview

Liquid template engine for PHP Build Status

Liquid is a PHP port of the Liquid template engine for Ruby, which was written by Tobias Lutke. Although there are many other templating engines for PHP, including Smarty (from which Liquid was partially inspired), Liquid had some advantages that made porting worthwhile:

  • Readable and human friendly syntax, that is usable in any type of document, not just html, without need for escaping.
  • Quick and easy to use and maintain.
  • 100% secure, no possibility of embedding PHP code.
  • Clean OO design, rather than the mix of OO and procedural found in other templating engines.
  • Seperate compiling and rendering stages for improved performance.
  • Easy to extend with your own "tags and filters":https://github.com/harrydeluxe/php-liquid/wiki/Liquid-for-programmers.
  • 100% Markup compatibility with a Ruby templating engine, making templates usable for either.
  • Unit tested: Liquid is fully unit-tested. The library is stable and ready to be used in large projects.

Why Liquid?

Why another templating library?

Liquid was written to meet three templating library requirements: good performance, easy to extend, and simply to use.

Installing

You can install this lib via composer:

composer create-project liquid/liquid

Example template

{% for product in products %}
  • {{ product.name }}

    Only {{ product.price | price }} {{ product.description | prettyprint | paragraph }} {{ 'it rocks!' | paragraph }}
  • {% endfor %} {% endif %}">
    {% if products %}
    	
       
      {% for product in products %}
    • {{ product.name }}

      Only {{ product.price | price }} {{ product.description | prettyprint | paragraph }} {{ 'it rocks!' | paragraph }}
    • {% endfor %}
    {% endif %}

    How to use Liquid

    The main class is Liquid::Template class. There are two separate stages of working with Liquid templates: parsing and rendering. Here is a simple example:

    render(array('name' => 'World'); // Will echo // Hello, World!">
    use Liquid\Template;
    
    $template = new Template();
    $template->parse("Hello, {{ name }}!");
    echo $template->render(array('name' => 'World');
    
    // Will echo
    // Hello, World!
    

    To find more examples have a look at the examples directory or at the original Ruby implementation repository's wiki page.

    Requirements

    • PHP 5.3+

    Issues

    Have a bug? Please create an issue here on GitHub!

    https://github.com/harrydeluxe/php-liquid/issues

    Fork notes and contributors

    This fork is based on php-liquid by Mateo Murphy. kalimatas has contributed a lot in his fork to bring Liquid to the new state. Thank you so much!

    It contains several improvements:

    • namespaces
    • installing via composer
    • new standard filters
    • raw tag added

    Any help is appreciated!

    Comments
    • refactor math filters to permit float variables (as ruby lib does)

      refactor math filters to permit float variables (as ruby lib does)

      Test template

      plus = {{ 0.5 | plus: 1 }}
      minus = {{ 0.5 | minus: 0.25 }}
      times = {{ 0.5 | times: 0.25 }}
      divided_by = {{ 0.5 | divided_by: 2 }}
      

      Results in both my fork, and ruby liquid

      plus = 1.5
      minus = 0.25
      times = 0.125
      divided_by = 0.25
      
      opened by kodekrash 3
    • Unkown tag continue

      Unkown tag continue

      It seems continue is not supported? Use case:

        {% for plan in site.data.public_plans %}
          {% if plan[1].slug == "sandbox" and showSandboxPlan == false %}
            {% continue %}
          {% endif %}
        {% endfor %}
      
      opened by kvz 3
    • Standardize date(), url_decode(), divided_by(), minus(), plus(), times()

      Standardize date(), url_decode(), divided_by(), minus(), plus(), times()

      To match the expected behavior of the original Ruby lib:

      date() - returns empty value if $input is empty url_decode() - currently missing divided_by(), minus(), plus(), times() - all use floats instead of ints

      opened by schmoove 2
    • Math filters always return whole integers

      Math filters always return whole integers

      So if you do:

      {{ 1 | plus: 1.5 }}

      You will get 2

      I would recommend the (int) type castings for values returned by the Math Filters be changed to (float) to avoid this.

      I'm pretty sure it's not the behaviour of the original Liquid implementation.

      opened by schmoove 2
    • Duplicated codebase hinders functionality.

      Duplicated codebase hinders functionality.

      Objects properties were unable to be accessed due to misplaced code.

      The chunk of code removed (lines 272..279) rendered the following (308..350) useless in case of an object variable.

      Now, I can safely do as follows:

        class Foo 
        {
          public $bar = "Hello World!";
        }
        $assigns = array('foo' => new Foo);
        print $liquid->render($assigns);
      

      and then access the property in the template with:

        {{ foo.bar }}
      

      Otherwise, it just throwed the LiquidException with message Method 'toLiquid' not exists!

      opened by maddes 2
    • What is this SPL extension? How do I know I have it?

      What is this SPL extension? How do I know I have it?

      Hi Harry,

      I know my php version by going to my terminal typing php -v which currently stands at 5.3.2

      however, i do not understand this SPL extension. How do i check if i have it?

      thank you.

      opened by simkimsia 2
    • is this updated??

      is this updated??

      Hi there Harry,

      i googled for a php port of liquid and i found yours AND https://github.com/m3talsmith/php-liquid

      may i know:

      1. are you still updating this project?

      2. which one should i use?

      thank you.

      opened by simkimsia 2
    • 500 error in response in codeigniter.

      500 error in response in codeigniter.

      Hi @harrydeluxe

      Thanks for this package. I have used this package in my localhost and its working fine. Now I want to use this package in CodeIgniter, so I have added this package at this path "application/third_party/php-liquid-compiler/liquid". And now I have created a library for using this package.

      Here is my library code, This code inside in "application/libraries/".

      <?php 
      if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
      class Phpliquidcompiler
      {
          public function phpLiquid(){
              $path = __DIR__ . "/../third_party/php-liquid-compiler/liquid/";
              $loader = require  $path . 'vendor/autoload.php';
              $loader->addPsr4('Liquid\\',  $path . 'src/Liquid');
              
              print_r($loader);
              use Liquid\Liquid;    // At here I getting 500 error.
              use Liquid\Template; 
      
      	Liquid::set('INCLUDE_SUFFIX', '');
      	Liquid::set('INCLUDE_PREFIX', '');
      	Liquid::set('INCLUDE_ALLOW_EXT', true);
      	Liquid::set('ESCAPE_BY_DEFAULT', true);
      
      	$liquid = new Template();
      	$liquid->parse('{% assign special= "sd" %} {% if special != "" %} <div><a
      	href="">[special]sdsdsd</a></div> {% endif %}');
      	echo $liquid->render();
          }
      }
      ?>
      

      Calling above code from controller.

      <?php
      defined('BASEPATH') OR exit('No direct script access allowed');
      
      class Welcome extends CI_Controller{
          public function index(){
      	$this->load->library('phpliquidcompiler');
              $this->phpliquidcompiler->phpLiquid();
          }
      }
      
      ?>
      

      Will you please tell me where I am wrong ?

      Thanks.

      opened by vishal-px 1
    • How to register an Extended AbstractTag?

      How to register an Extended AbstractTag?

      Title says it all. I want to add a new tag, callable by {% entypo %} and I can't figure out how to register a AbstractTag. Here's the tag:

      <?php
      
          namespace CMS\Liquid;
      
          use Liquid\AbstractTag;
      
          class EntypoTag extends AbstractTag {
                  public function __construct($markup, array &$tokens, FileSystem $fileSystem = null) {
                      parent::__construct($markup, $tokens, $fileSystem);
                  }
      
                  public function render(Context $context) {
                      die($context);
                  }
          }
      

      And here is how I'm registering it so far:

       $template = new Template();
       $template->parse(file_get_contents(__DIR__.'/../src/views/admin/dashboard.html'));
       $template->registerTag('entypo', new EntypoTag('entypo',$template->tokens));
      
       echo $template->render();
      

      And bam, I get a Unkown tag entypo [E:\Webdev\CMS\vendor\liquid\liquid\src\Liquid\AbstractBlock.php:146]. How can I propely register it?

      opened by randohinn 1
    • Context tries to access private properties where public methods exists

      Context tries to access private properties where public methods exists

      Consider the following class definition.

      class Example
      {
      	private $name = null;
      
      	public function name()
      	{
      		return $this->name;
      	}
      }
      

      If you happen to include an instance of this class in a template, then try to access the name like so:

      {{ example.name }}
      

      You will get a fatal error:

      PHP Fatal error:  Uncaught Error: Cannot access private property Example::$name
      
      opened by sanmai 1
    • Quotes (escaped) inside

      Quotes (escaped) inside "filtered" text or inside a filter's arguments

      Example of trying to filter some text that has double escaped quotes inside of it:

      {{ "let's try some \"quoted\" text" | my_filter }}

      Example of trying to filter some text using an argument that has double escaped quotes inside of it:

      {{ "text" | my_filter: "let's try some \"quoted\" argument" }}

      These are scenarios that I have come across and it appears that the text and argument are both cut off at the first backslash \ because both 'QUOTED_STRING' => '"[^"]*"|\'[^\']*\'' and 'QUOTED_STRING_FILTER_ARGUMENT' => '"[^":]*"|\'[^\':]*\'', are greedy and stop after the first double quote " they find.

      It seems that something like this might be a solution:

      In \Liquid\Liquid change QUOTED_STRING and QUOTED_STRING_FILTER_ARGUMENT as follows:

      'QUOTED_STRING' => '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'',
      'QUOTED_STRING_FILTER_ARGUMENT' => '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'',
      

      Thanks @bigwhoop for help on this.

      opened by dovid 1
    • Maintenance the project

      Maintenance the project

      Hi

      Why not maintenance and archived? It's really good project, I personally love to use Liquid template engine.

      If you not have time to work, Maybe someone can join to work? There is anyone?

      Best, M.

      opened by BaseMax 2
    • Unknown tag render

      Unknown tag render


      Fatal error: Uncaught Liquid\Exception\ParseException: Unknown tag render in /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/AbstractBlock.php:210 Stack trace: #0 /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/AbstractBlock.php(88): Liquid\AbstractBlock->unknownTag('render', ''ObservationVit...', Array) #1 /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/Document.php(32): Liquid\AbstractBlock->parse(Array) #2 /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/Template.php(213): Liquid\Document->__construct(Array, Object(Liquid\LocalFileSystem)) #3 /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/Template.php(188): Liquid\Template->parseAlways('{\n "resource...') #4 /Applications/MAMP/htdocs/ehr_uphc/liquid/OPConsultRecord.php(194): Liquid\Template->parse('{\n "resource...') #5 {main} thrown in /Applications/MAMP/htdocs/ehr_uphc/liquid/src/Liquid/AbstractBlock.php on line 210
      opened by Harsha-Madiraju 0
    • Colon not allowed in date format string?

      Colon not allowed in date format string?

      Hello,

      It seems as though {{ "now" | date: "%Y-%m-%d %H:%M" }} renders null but {{ "now" | date: "%Y-%m-%d %H%M" }} renders just fine. Is anyone else having this issue? It seems that the colon is causing it to render null.

      opened by sml1990 1
    • Disable Casesensitive

      Disable Casesensitive

      When the data is:

      $data = ["something" => "value"];

      And using: {{Something}}

      The replacement not working.

      Where I need to add strtolower before to disable the Casesensitive?

      Thanks

      opened by CBox 0
    Owner
    Harald Hanek
    If it’s in the browser, i can do it.
    Harald Hanek
    PHP template engine for native PHP templates

    FOIL PHP template engine, for PHP templates. Foil brings all the flexibility and power of modern template engines to native PHP templates. Write simpl

    Foil PHP 167 Dec 3, 2022
    Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.

    Smarty 3 template engine smarty.net Documentation For documentation see www.smarty.net/docs/en/ Requirements Smarty can be run with PHP 5.2 to PHP 7.4

    Smarty PHP Template Engine 2.1k Jan 1, 2023
    ☕ Latte: the intuitive and fast template engine for those who want the most secure PHP sites.

    Latte: amazing template engine for PHP Introduction Latte is a template engine for PHP which eases your work and ensures the output is protected again

    Nette Foundation 898 Dec 25, 2022
    View template engine of PHP extracted from Laravel

    Blade 【简体中文】 This is a view templating engine which is extracted from Laravel. It's independent without relying on Laravel's Container or any others.

    刘小乐 143 Dec 13, 2022
    ⚡️ Simple and fastly template engine for PHP

    EasyTpl ⚡️ Simple and fastly template engine for PHP Features It's simple, lightweight and fastly. No learning costs, syntax like PHP template It is s

    PHPPkg 19 Dec 9, 2022
    Twig Template Engine to Phalcon PHP

    Twig Template Engine to Phalcon PHP

    Vinicius 4 Oct 7, 2022
    Pug (Jade) template engine for Symfony

    Pug-Symfony Pug template engine for Symfony This is the documentation for the ongoing version 3.0. Click here to load the documentation for 2.8 Instal

    Pug PHP 41 Dec 16, 2022
    PHPlater, a simple template engine.

    PHPlater A simple PHP template engine that lets PHP do all the logic and then append it to the HTML in the template file. It is set to solve the probl

    John Larsen 2 Jun 3, 2022
    A template abstraction prototype for PHP template engines

    Schranz Templating A template abstraction prototype for PHP template engines. This project should help to find a way for a general Template Render Int

    Schranz Templating 16 Dec 7, 2022
    Standalone Skeltch templating engine for PHP

    SkeltchGo is a standalone version of Glowie Skeltch templating engine for PHP, intented to use from outside the framework.

    glowie 1 Nov 5, 2021
    SwitchBlade: Custom Directives for the Laravel Blade templating engine

    SwitchBlade: Custom Directives for the Laravel Blade templating engine

    Awkward Ideas 10 Nov 29, 2022
    Experimental ActiveRecord layer on top of Doctrine2 using the Twig templating engine

    This is an experiment for building ActiveRecord functionality on top of Doctrine2 using the Twig templating engine. Whether it is called Propel2 or not is irrelevant.

    Francois Zaninotto 85 Dec 5, 2022
    A PHP project template with PHP 8.1, Laminas Framework and Doctrine

    A PHP project template with PHP 8.1, Laminas Framework and Doctrine

    Henrik Thesing 3 Mar 8, 2022
    Twig, the flexible, fast, and secure template language for PHP

    Twig, the flexible, fast, and secure template language for PHP Twig is a template language for PHP, released under the new BSD license (code and docum

    Twig 7.7k Jan 1, 2023
    Native PHP template system

    Plates Plates is a native PHP template system that's fast, easy to use and easy to extend. It's inspired by the excellent Twig template engine and str

    The League of Extraordinary Packages 1.3k Jan 7, 2023
    A complete and fully-functional implementation of the Jade template language for PHP

    Tale Jade for PHP Finally a fully-functional, complete and clean port of the Jade language to PHP — Abraham Lincoln The Tale Jade Template Engine brin

    Talesoft 91 Dec 27, 2022
    A ready-to-use Model View Controller template in PHP

    PHP-MVC-Template A ready-to-use Model View Controller template in PHP Use this repo as a template! (Or clone it) Start to configure your MVC file Afte

    Loule | Louis 20 Dec 26, 2022
    Provides a GitHub repository template for a PHP package, using GitHub actions.

    php-package-template Installation ?? This is a great place for showing how to install the package, see below: Run $ composer require ergebnis/php-pack

    null 280 Dec 27, 2022
    The free-to-use template for your Imagehost-website made with PHP, HTML and CSS!

    The free-to-use template for your Imagehost-website made with PHP, HTML and CSS! Some information before we start This repo is only code related, to a

    Ilian 6 Jul 22, 2022