Giter Club home page Giter Club logo

templateenginetwig's Introduction

TemplateEngineTwig

Build Status StyleCI License: MIT ProcessWire 3

A ProcessWire module adding Twig to the TemplateEngineFactory.

Requirements

  • ProcessWire 3.0 or newer
  • TemplateEngineFactory 2.0 or newer
  • PHP >= 7.0 for version 2.x, PHP >= 7.2.5 for version 3.x
  • Composer

The 1.x version of this module is available on the 1.x branch. Use this version if you still use TemplateEngineFactory 1.x.

Installation

Execute the following command in the root directory of your ProcessWire installation:

composer require wanze/template-engine-twig:^3.0

This will install the TemplateEngineTwig and TemplateEngineFactory modules in one step. Afterwards, don't forget to enable Twig as engine in the TemplateEngineFactory module's configuration.

ℹ️ This module includes test dependencies. If you are installing on production with composer install, make sure to pass the --no-dev flag to omit autoloading any unnecessary test dependencies!.

Configuration

The module offers the following configuration:

  • Template files suffix The suffix of the Twig template files, defaults to twig.html.
  • Provide ProcessWire API variables in Twig templates API variables ($pages, $input, $config...) are accessible in Twig, e.g. {{ config }} for the config API variable.
  • Debug If enabled, Twig outputs debug information. The module also registers the Debug Extension, offering the {{ dump() }} function to inspect variables.
  • Auto reload templates (recompile) If enabled, templates are recompiled whenever the source code changes.
  • Strict variables If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead
  • Auto escape variables If enabled, templates will auto-escape variables. If you are using ProcessWire textformatters to escape field values, do not enable this feature.

Extending Twig

It is possible to extend Twig after it has been initialized by the module. Hook the method TemplateEngineTwig::initTwig to register custom functions, extensions, global variables, filters etc.

Here is an example how you can use the provided hook to attach a custom function.

wire()->addHookAfter('TemplateEngineTwig::initTwig', function (HookEvent $event) {
    /** @var \Twig\Environment $twig */
    $twig = $event->arguments('twig');

    $twig->addFunction(new \Twig\TwigFunction('processwire', function () {
        return 'ProcessWire rocks!';
    }));
});

// ... and then use it anywhere in a Twig template:

{{ processwire() }}

The above hook can be put in your site/init.php file. If you prefer to use modules, put it into the module's init() method and make sure that the module is auto loaded.

Use Twig Extensions

The Twig Extensions is a library that provides several useful extensions for Twig.

These extensions are not included in the module by default, but you can add them to Twig using the same hook explained above.

Fist, install the library with Composer in the ProcessWire root directory: composer require twig/extensions. Next, use the same hook as above to register the desired extensions.

wire()->addHookAfter('TemplateEngineTwig::initTwig', function (HookEvent $event) {
    /** @var \Twig\Environment $twig */
    $twig = $event->arguments('twig');
    
    // Register the extensions.
    $twig->addExtension(new Twig_Extensions_Extension_Text());
    $twig->addExtension(new Twig_Extensions_Extension_I18n());
    $twig->addExtension(new Twig_Extensions_Extension_Intl());
});

templateenginetwig's People

Contributors

dharmastyle avatar gmclelland avatar harikt avatar hiboudev avatar porl avatar rudyaffandi avatar siphomateke avatar wanze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

templateenginetwig's Issues

Strange field label

I'm not sure why, but I'm seeing a weird label when I visit the module's configuration page.
See this image:
twig

FormBuilder and twig template

Using v2 of twig and latest version of Form Builder pro module. When trying to display the easy embed (Iframe) method on a page, or in the backend, I get an error:

Error: Exception: Unable to find template "form-builder.twig" (looked into: /srv/users/serverpilot/apps/xxappnameremovedxx/public/site/templates/views). (in /srv/users/serverpilot/apps/xxappnameremovedxx/public/vendor/twig/twig/src/Loader/FilesystemLoader.php line 250)

Past versions of twig did not display this error and just displayed the form-builder.php code. I can't exclude the form-builder template in the Factory settings as it is a system template.

Deprecation warning message

@wanze, I got this warning message, FYI

E_USER_DEPRECATED  Using Twig_Autoloader is deprecated since version 1.21. Use Composer instead. - /Users/####/Sites/#####/public/site/modules/TemplateEngineTwig/vendor/twig/twig/lib/Twig/Autoloader.php:30
(anonymous) @ content.js:3
EventImpl.dispatchToListener @ VM6929 extensions::event_bindings:380
publicClassPrototype.(anonymous function) @ VM6935 extensions::utils:149
EventImpl.dispatch_ @ VM6929 extensions::event_bindings:364
EventImpl.dispatch @ VM6929 extensions::event_bindings:386
publicClassPrototype.(anonymous function) @ VM6935 extensions::utils:149
messageListener @ VM6936 extensions::messaging:215
EventImpl.dispatchToListener @ VM6929 extensions::event_bindings:380
publicClassPrototype.(anonymous function) @ VM6935 extensions::utils:149
EventImpl.dispatch_ @ VM6929 extensions::event_bindings:364
EventImpl.dispatch @ VM6929 extensions::event_bindings:386
publicClassPrototype.(anonymous function) @ VM6935 extensions::utils:149
dispatchOnMessage @ VM6936 extensions::messaging:339

Update documentation

On this page: https://processwire.com/modules/template-engine-twig/

  • Current version is v3, not v2.

  • This code is wrong:

wire()->addHookAfter('TemplateEngineTwig::initTwig', function (HookEvent $event) {
    /** @var \Twig_Environment $twig */
    $twig = $event->arguments('twig');
    $twig->addFunction(new \Twig_Function('processwire', function () {
        return 'ProcessWire rocks!';
    }));
});

This one is OK:

wire()->addHookAfter('TemplateEngineTwig::initTwig', function (HookEvent $event) {
    /** @var \Twig\Environment $twig */
    $twig = $event->arguments('twig');
    $twig->addFunction(new \Twig\TwigFunction('processwire', function () {
        return 'ProcessWire rocks!';
    }));
});

Fix deprecation warnings for PHP 8.2

Warning in PW admin when installing module in PHP 8.1:

Deprecated: Using ${var} in strings is deprecated, use {$var} instead in site\modules\TemplateEngineTwig\src\TemplateEngineTwig.php on line 128

Loading problem with cached files

Hey,

on my local machine with MAMP Pro I get the following error when building templates with the Factory and Twig as Engine:

Fehler parsen: syntax error, unexpected ',', expecting end of file (Zeile 135 in web/public/site/assets/cache/TemplateEngineTwig_compile/0d/0dda3e76ea43f2f2df3aa71e24c2fbb25c24c60c5f28e22c1f88bb9f8c815c63.php)

When I delete the commented Markup in the cached file everything works as expected. Is there any way to disable the Markup Comment in the cached file?

The cached file looks like that:

<?php

/* layouts/master.twig */
class __TwigTemplate_f246c3b34b0d6f1239cb975181e9cb0774fdbeef1d284a84fa5d6c7b120ed7fb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'header' => array($this, 'block_header'),
            'content' => array($this, 'block_content'),
            'footer' => array($this, 'block_footer'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "<!doctype html>
<html class=\"no-js\" lang=\"\">
<head>
    <meta charset=\"utf-8\">
    <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\">
    <title></title>
    <meta name=\"description\" content=\"\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">

    <link rel=\"apple-touch-icon\" href=\"apple-touch-icon.png\">
    <!-- Place favicon.ico in the root directory -->

    <link rel=\"stylesheet\" href=\"css/normalize.css\">
    <link rel=\"stylesheet\" href=\"css/main.css\">
    <script src=\"js/vendor/modernizr-2.8.3.min.js\"></script>
</head>
<body>
<!--[if lte IE 9]>
<p class=\"browserupgrade\">You are using an <strong>outdated</strong> browser. Please <a href=\"http://browsehappy.com/\">upgrade
    your browser</a> to improve your experience and security.</p>
<![endif]-->

<!-- Add your site or application content here -->
";
        // line 24
        $this->displayBlock('header', $context, $blocks);
        // line 27
        echo "
<div class=\"c-main\">
    <div class=\"c-main__inside o-wrapper\">
        ";
        // line 30
        $this->displayBlock('content', $context, $blocks);
        // line 33
        echo "    </div>
</div>

<div class=\"c-footer\">
    <footer class=\"c-footer__inside o-wrapper\">
        ";
        // line 38
        $this->displayBlock('footer', $context, $blocks);
        // line 41
        echo "    </footer>
</div>

<script src=\"https://code.jquery.com/jquery-3.1.0.min.js\"></script>
<script>window.jQuery || document.write('<script src=\"js/vendor/jquery-3.1.0.min.js\"><\\/script>')</script>
<script src=\"js/plugins.js\"></script>
<script src=\"js/main.js\"></script>

</body>
</html>";
    }

    // line 24
    public function block_header($context, array $blocks = array())
    {
        // line 25
        echo "    ";
        $this->loadTemplate("partials/header.twig", "layouts/master.twig", 25)->display($context);
    }

    // line 30
    public function block_content($context, array $blocks = array())
    {
        // line 31
        echo "            Content
        ";
    }

    // line 38
    public function block_footer($context, array $blocks = array())
    {
        // line 39
        echo "            Footer
        ";
    }

    public function getTemplateName()
    {
        return "layouts/master.twig";
    }

    public function getDebugInfo()
    {
        return array (  97 => 39,  94 => 38,  89 => 31,  86 => 30,  81 => 25,  78 => 24,  65 => 41,  63 => 38,  56 => 33,  54 => 30,  49 => 27,  47 => 24,  22 => 1,);
    }
}
/* <!doctype html>*/
/* <html class="no-js" lang="">*/
/* <head>*/
/*     <meta charset="utf-8">*/
/*     <meta http-equiv="x-ua-compatible" content="ie=edge">*/
/*     <title></title>*/
/*     <meta name="description" content="">*/
/*     <meta name="viewport" content="width=device-width, initial-scale=1">*/
/* */
/*     <link rel="apple-touch-icon" href="apple-touch-icon.png">*/
/*     <!-- Place favicon.ico in the root directory -->*/
/* */
/*     <link rel="stylesheet" href="css/normalize.css">*/
/*     <link rel="stylesheet" href="css/main.css">*/
/*     <script src="js/vendor/modernizr-2.8.3.min.js"></script>*/
/* </head>*/
/* <body>*/
/* <!--[if lte IE 9]>*/
/* <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade*/
/*     your browser</a> to improve your experience and security.</p>*/
/* <![endif]-->*/
/* */
/* <!-- Add your site or application content here -->*/
/* {% block header %}*/
/*     {% include 'partials/header.twig' %}*/
/* {% endblock %}*/
/* */
/* <div class="c-main">*/
/*     <div class="c-main__inside o-wrapper">*/
/*         {% block content %}*/
/*             Content*/
/*         {% endblock %}*/
/*     </div>*/
/* </div>*/
/* */
/* <div class="c-footer">*/
/*     <footer class="c-footer__inside o-wrapper">*/
/*         {% block footer %}*/
/*             Footer*/
/*         {% endblock %}*/
/*     </footer>*/
/* </div>*/
/* */
/* <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>*/
/* <script>window.jQuery || document.write('<script src="js/vendor/jquery-3.1.0.min.js"><\/script>')</script>*/
/* <script src="js/plugins.js"></script>*/
/* <script src="js/main.js"></script>*/
/* */
/* </body>*/
/* </html>*/

Thanks, and I hope you can help @wanze

Parse Error: syntax error, unexpected ',' (line 99 of <file>)

Hello there,

I get the error from above.

The templates are okay, if i delete the cache and reload the page everything works fine, after the next refresh of the page this error appears.

The file has on the specified line the following content.
/* {% include "shared/_header.twig" %}*/

So this cannot be the problem.

I´m using

  • ProcessWire 3.0.42
  • TemplateEngineFactory 1.1.1
  • TemplateEngineTwig 1.0.4

any suggestion how to fix this issue?

Can not access ID of a FieldtypeOptions option

I'm using the default PW "Select Options" component and when trying to get ID of the option from a Twig, it throws an error:

Fatal Error: Uncaught ArgumentCountError: Too few arguments to function SelectableOptionArray::hasID(), 0 passed in E:\path\vendor\twig\twig\src\Extension\CoreExtension.php on line 1635 and exactly 1 expected in E:\path\wire\modules\Fieldtype\FieldtypeOptions\SelectableOptionArray.php:262

#0 E:\path\vendor\twig\twig\src\Extension\CoreExtension.php(1635): SelectableOptionArray->hasID()
#1 E:\path\site\assets\cache\TemplateEngineTwig_compile\72\7271faee4ef038b8f49fabbd4afa01b2.php(137): twig_get_attribute(Object(Twig\Environment), Object(Twig\Source), Object(SelectableOptionArray), 'id', Array, 'any', false, false, false, 53)

Code:
{{ user.membershipStatus.id }}

The same code in PHP works fine:
$user->membershipStatus->id

Can't use engine( please help

Fatal Error: Uncaught Error: Class 'Twig_Loader_Filesystem' not found in /Users/Regesh/Sites/localhost/site/modules/TemplateEngineTwig/src/TemplateEngineTwig.php:51
if select smart - the same(
thanks

Remove the vendor directory

After spending some time trying to fix the TwigExtensions module, I think we should remove the Vendor directory from this module and the TwigExtensions module and rely on Composer only to install all dependencies.

The problem I ran into was that the TwigExtensions module also includes a composer.json that only list "twig/extensions": "~1.5" as a dependency. The problem with that is that Twig is a dependency of twig/extensions. So the TwigExtension module was loading a version of Twig in it's module that wasn't the same as the version of Twig in the TemplateEngineTwig module which was causing the PHP errors. Ideally there should only be one version of Twig loaded.

I know it's a little inconvenient to "composer require twig/twig:1.35" before you install this module, but I think it's for the better.

  • This module will be smaller in size because it won't include harikt's code and the Twig library
  • You won't have to update this module every time there is a security update in the Twig library (more secure)

Before I typed up this issue, I tried adding harikt's code to the TwigExtensions module:

{
    "name": "justb3a/processwire-twigextensions",
    "type": "pw-module",
    "description": "ProcessWire module that allows customizing twig, e.g. add extensions",
    "keywords": [ "twig-engine", "processwire"],
    "homepage": "https://github.com/justb3a/processwire-twigextensions",
    "license": "GPL-2.0",
    "authors": [
        {
            "name": "ProcessWire Twig Extensions Contributors",
            "homepage": "https://github.com/justb3a/processwire-twigextensions/contributors"
        }
    ],
    "require": {
        "php": ">=5.3.0",
        "hari/pw-module": "~1.0",
        "wanze/template-engine-twig": "~1.0",
        "twig/twig": "~1.35",
        "twig/extensions": "~1.5"
    }
}

But I noticed when I ran "composer update" from the TwigExtensions module directory, it would include a site/modules/TemplateEngineFactory and site/modules/TemplateEngineTwig folders as well as the vendor libraries in the Vendor directory.

That means every time there is change in TemplateEngineTwig's Twig library, the TwigExtensions module would also have to keep the same version of Twig in sync. The module author would also have to delete the newly created "site" folder as well before committing the library changes to git.

This could be prevented if both modules would remove their Vendor director and rely on Composer to have the user install the dependencies in the site root's Vendor directory.

Here's Ryan's thoughts on how to use composer:

Here's Hari's

What do you think?

filter trim is broken

After upgrading TemplateEngineTwig from 1.0.4 to 1.1.0 i get a problem with {% filter trim %}{% endfilter %}. Instead of trimming the string, i get another unrelated string (Page Title) as a replacement. Removing the filter, I get back the expected untrimmed string.

PHP 7.1.12, ProcessWire 3.0.98, Cache Folder cleared

Errors with 1.1.0

Hi @wanze,

Just wanted to let you know that I tried upgrading to the latest version, but I'm getting the following error:

Exception: An exception has been thrown during the compilation of a template ("Object of class Twig_Source could not be converted to string") in {}. (in /Users/glenn/websites/mywebsite/wwwroot/site/assets/cache/FileCompiler/site/modules/TemplateEngineTwig/TemplateEngineTwig.module line 94)

error

I tried refreshing the modules and clearing compiled files from the admin. Is there anything else I need to do or try?

I'm running php 7.1. I also have the latest version TemplateEngineFactory installed. I'm running Processwire 3.0.96

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.