Jump to content

Module: TemplateEngineFactory


Recommended Posts

Updated the module to version 1.1.0 which adds the following features:

  • Multiple data can be passed to the template engine via setArray() (alias: setMultiple())
  • The module now provides a second API variable $factory returning the singleton instance of the TemplateEngineFactory, which can be used to load partial views and chunks
  • Chunks: Reusable code snippets that consist of a PHP file containing the logic and a template (view) to render the output (see https://github.com/wanze/TemplateEngineFactory#chunks)

Thanks @justb3a for the contributions! Twig and Smarty modules were updated as well, shipping with the newest version of Twig/Smarty.

I tested the module on the latest ProcessWire 2.7 and 3.x and everything worked fine. Let me know if you find any issues!


  • Like 4
Link to comment
Share on other sites

  • 4 weeks later...
  • 4 months later...


I am newbie on Processwire an I am using your module with smarty renderer. It works good but I have a difficulty.

My Processwire page tree :

  1. Home (template = home.tpl)
    1. page 1 (template = basic_page.tpl)
    2. special page (template = special.tpl)

I used an extended template 'template.tpl' in special.tpl and a global controller _init.php width the nav definition.

How to do that : if I go to http://mywebsite.com/ (then get home.tpl rendering), I would like to have the render result from "special page" with "special.tpl".

Sorry for my poor english language ;-)

Thx in advance



Link to comment
Share on other sites

Hi Besen,

So if you visit the homepage of your website, you basically want to display the same as when you visit your special page? Why not use your special page as homepage (thus moving controller logic from site/templates/special.php to site/templates/home.php) and also the smarty template?

Otherwise you could try the following:

  1. Rename home.tpl to home.tpl.temp - The factory won't attach hooks to delegate the rendering to smarty, as no template is found
  2. In your site/templates/home.php controller add the following: echo $pages->get('/special-page/')->render();

I'm not sure if it works though...


Link to comment
Share on other sites

I keep getting a cache error. I can delete cache then page loads then won't load again as new cache is created. Any ideas as to why this is happening?

Parse Error: syntax error, unexpected ',' (line 44 of /home4/subtlem2/public_html/vocalcoach.rede-commerce.com/site/assets/cache/TemplateEngineTwig_compile/66/664c8e217f20e0ab2fed758d06f848fe2e2306d2a4af4cd131d4155af1b015e0.php)

This error message was shown because: site is in debug mode. ($config->debug = true; => /site/config.php). Error has been logged.

Link to comment
Share on other sites

@SubMon I assume you are using ProcessWire 3.x? Check out this comment: 


You need to disable the FileCompiler for your twig templates. There's currently no way for the module to tell the compiler to ignore these files, so at the moment this seems like the only solution. However, there is a pull request open to support this and I hope it's getting integrated soon.


  • Like 1
Link to comment
Share on other sites


When I'm using this code in a controller, the prepend file (_init.php) is not running.

// ======= basic-page.php =======
// SET ACTIVE NAV (used by _init.php prepend file
$view->set('menuActive', $page->name);

if ($page->children->get('template=portfolio')) {
  $view = $factory->load('portfolio', true); // Load the main markup

How can I set the prepend file running ?

Thanks in advance

Link to comment
Share on other sites


The _init.php file isn't processed when loading views. Basically this file is only loaded by ProcessWire when you load a ProcessWire template file (controller). So in the current situation, _init.php was called before your basic-page.php controller was loaded.

I'm not sure what you're trying to do, could you elaborate a bit? Do you want to render a portfolio in your current basic-page template?

Link to comment
Share on other sites

In this case you can make use of partial templates or chunks.


$view->set('menuActive', $page->name);
$portfolio = $page->children->get('template=portfolio');
$portfolio_partial = $factory->load('partials/portfolio');
$portfolio->set('title', $portfolio->title);
$portfolio->set('body', $portfolio->body);
$view->set('portfolio', $portfolio->render());


Hope this helps!


Link to comment
Share on other sites

  • 7 months later...

I'm reposting this from Github - I have the same problem:



I'm setting my template file based on a condition and use $view->setFilename.


if($format == 'json') {
} else {

Because of this reason I don't need an .tpl file for each Processwire template.
E.g. If I have in Processwire a tempalte called "home", I have to add an emtpy views/home.tpl file to make smarty work for me. If not i would get an empty white page - also if I do $view->setFilename('my-tempalte/json.tpl');

I don't want to blow up my views folder with so much empty files.

Is there a way to avoid this when using $view->setFilename?


Link to comment
Share on other sites

  • 4 weeks later...

Hello, I'd like to know how to set the layout block logic for the ProcessWire side (the default one) of the templates. That is, twig uses {% block content %}, Jade uses block content, PW... ?

Also, is there documentation of the module for using PW as the main language? I checked the forums but found none...

Thank you very much

Link to comment
Share on other sites

3 hours ago, Manaus said:

Hello, I'd like to know how to set the layout block logic for the ProcessWire side (the default one) of the templates. That is, twig uses {% block content %}, Jade uses block content, PW... ?

Also, is there documentation of the module for using PW as the main language? I checked the forums but found none...

Thank you very much

This block thingy are features of the template engines (twig, smarty, jade...). ProcessWire does not offer this, you may look at regions, though I've never used them. This module does not implement any new features, it just serves to connect different template engines to ProcessWire and to use them via a common interface.

If you use ProcessWire as template engine, you get all the features of ProcessWire templates: http://processwire.com/api/templates/


  • Like 1
Link to comment
Share on other sites

  • 1 month later...

I used a simple TemplateFile extension to build a similar module which works fine with ajax (load current page / page part without global layout).

The module is small and simple: 

But maybe it would be better to move to your TemplateEngineFactory because it's well written and much more flexible. I think it would be better to have one base instead of different modules with the same goal. ;)

  1. TemplateEngineFactory supports global template / layout. So it outputs the current page inside of a global layout template. 
    Is it possible to skip that for ajax usage? Just output the current page part if it was a ajax call?
  2. Add cache feature to Processwire engine should be easy with WireCache? Or wouldn't it be a good option?
  3. At the moment it isn't needed. What's about multi lang and caching)?
  4. scripts / styles in global or current page context? For example to handle just current page scripts and styles if requested by a ajax call.
Link to comment
Share on other sites

Hi Wanze,

first of all a big thank you for this great module which I stumbled upon a few days ago.

I also have some questions regarding the flexibility of TemplateEngineFactory. Let me explain what I was trying to achieve (using Smarty, but I think this would apply to other template engines as well):

In a page of mine, there is a specific template whose output should be processed by a text filter before sending to the client browser. Also the processed output should be cached a specific amount of time (just output of pages based on this specific template).

What I tried:

  1. attach the text filter via a new module and a hook to Page::render(). With this approach I have to be careful to just apply the filter to the one specific type of pages and also (as the filter is CPU-intensive and the hook is executed at every page view) it does not work well with caching.
  2. attach the text filter via a hook to TemplateEngineSmarty::initSmarty(). Here I also have to be careful to not apply the filter to the wrong pages, caching with Smarty works but only with one global cache timeout config value. This is not acceptable for me because this would also affect pages based on other templates.

I then digged a bit in the source code of the module and had the following idea:

Why not provide a so-called 'direct' mode, globally enabled/disabled via module configuration. This direct mode does not attach the hook to Page::render() and lets the user choose when to output the markup via a method like $view->renderAndPrint(). Wouldn't ths also give back the possibility to control caching time per template via the template caching configuration? Also filters could be added right in the template source file before calling $view->renderAndPrint().

I am not sure If I thought this through entirely and not missed something and would appreciate any feedback on my suggestion.

Thank you in advance,



Link to comment
Share on other sites

  • 5 months later...

Hi @Menz

Sorry for my late response, I was traveling a longer time while you were posting this. I would be interested if you could solve it using the module? There is another approach which let's you control the caching:

1. Do not create a corresponding smarty template so that the module does not attach the render hook. This means that the controller aka regular ProcessWire template will work just normal. Let's call this template filter_response.php.

2. The filter_response.php can still use the factory to create the markup via Smarty but at the same time control the caching via WireCache.

Something like this (inside site/templates/filter_response.php)

if ($cached = $cache->getFor('my_namespace', $page->id) {
  echo $cached;
} else {
  $tpl = $factory->load('filetered_response_template');
  $tpl->page = $page;
  $output = $tpl->render();
  $output = filter_output($output);
  $cache->setFor('my_namespace', $page->id, $output);
  echo $output;


  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

Loving this module so far but I am having trouble using markup regions.

I have successfully got it to output markup using the ProcessWire template engine but can't figure out how to use markup regions. I have enabled

$config->useMarkupRegions = true;

and have the following files


<!DOCTYPE html>
    <div id='content'>
      <h1 id='headline'><?=$page->title?></h1>
      <div id='bodycopy'>
    <aside id='sidebar'>
    <footer id='footer'>
      <p>Copyright 2017</p>


<aside id='sidebar'>
  <p>Hello from home</p>

<?php include('../includes/_main.php')?>

as per the tutorial linked above. (I am not using any MVC features because I was trying to debug it)

I'm not a huge fan of Twig but I am a fan of MVC so if anybody could help me out it would be greatly appreciated.

Link to comment
Share on other sites

  • 2 weeks later...

I have two templates:

  1. basic-page
    1. title
    2. body
  2. calendar-posting
    1. title
    2. event_description

I'm trying to build a search page that can search for text in any of those fields.  Right now my selector looks like "title|body|event_description*=support, limit=3".  It correctly returns a Page Array when I perform a search.

I can output the page's title just fine, but the problem happens when I try to output the event_description field.  I get the following error:

User Error

Exception: An exception has been thrown during the rendering of a template ("Method Page::event_description does not exist or is not callable in this context") in "search.twig" at line 50. (in /Users/glenn/websites/mysite/wwwroot/site/assets/cache/FileCompiler/site/modules/TemplateEngineTwig/TemplateEngineTwig.module line 110)

Note: I am using the TemplateEngineTwig and TemplateEngineFactory modules.

In my search.twig

{% for post in paginated_items  %}
              <article class="card post">
                <div class="card-section">
                    <a href="{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a>
                  <div class="meta">
                    <p>{% if post.editable() %}
                      <a href="{{ config.urls('admin') }}page/edit/?id={{ post.id }}">Edit</a>
                    {% endif %}

                  {% if post.event_description %}
                    <div class="post-content">{{ post.event_description|striptags('<style>')|truncate(440, false, "...") }}
                      <a class="read-more" href="{{ post.url }}" title="{{ post.title }}">{{ 'Read More' }}</a>
                  {% endif %}
                </div><!-- card-section -->
{% endfor %}


Anyone have any ideas as to what could be the cause?

If the returned PageArray from my find returns two items, I should be able to access and output any of those page's fields right?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.

      This module is probably the most powerful module. You might destroy your processwire installation if you don't exactly know what you doing. Be careful and use it at your own risk!
      ACE code editor
      This module uses ACE code editor available from: https://github.com/ajaxorg/ace

      This module uses the JavaScript dragscroll available from: http://github.com/asvd/dragscroll. Dragscroll adds the ability to drag the table horizontally with the mouse pointer.
      PHP File Manager
      This module uses a modified version of PHP File Manager available from: https://github.com/alexantr/filemanager
    • By tcnet
      This module implements the website live chat service from tawk.to. Actually the module doesn't have to do much. It just need to inserted a few lines of JavaScript just before the closing body tag </body> on each side. However, the module offers additional options to display the widget only on certain pages.
      Create an account
      Visit https://www.tawk.to and create an account. It's free! At some point you will reach a page where you can copy the required JavaScript-code.

      Open the module settings and paste the JavaScript-code into the field as shown below. Click "Submit" and that's all.

      Open the module settings
      The settings for this module are located int the menu Modules=>Configure=>LiveChatTawkTo.

  • Create New...