Jump to content

Module: TemplateEngineFactory


Recommended Posts

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

Hi there.

Not sure if my problem is specific to the twig engine or to this factory module.

If I enable automatic rendering, I have no issues, however if I turn it off (and call the render function as follows), I can't use any '%' character in the template or in Processwire fields.

The render function is called like this:



$factory = $modules->get('TemplateEngineFactory');

printf($factory->render($page->template->name, $twigVars));


$twigVars is just an array I'm passing it (and tested working fine).

I have tried using Twig with raw php (no processwire) and the templates render fine (obviously without ProcessWire functionality), so I believe the $factory->render function may be trying to interpret the '%' character in some way.

The % character is fine to use within twig tags (including using {% and %}), but anywhere else the method just returns null.

I tried replacing these lines with calls to twig directly, which rendered the template fine, however it is unfortunately not a workaround for me as my templates are making calls to other page render functions (this is why I can't use auto render) and those are not getting the php template files called correctly as twig obviously doesn't know about this.

Link to comment
Share on other sites

  • 3 weeks later...

Hey @Wanze. I am wondering if I could request an additional empty "config" array in the render method. This would let TemplateEngine modules do some more logic their end, eg override module config settings.

The reason for this is for whatever reason I seem to find myself wanting to render template partials without worrying about or needing the global data object (just explicitly pass params), however I would also like the global data object populated generally. Eg...

<?php $factory->render('partial', ['foo' => 'bar'], ["global_data" => false] ));


Link to comment
Share on other sites

  • 2 weeks later...
  • 1 month later...


I'm using the excellent Template Engine Factory from @Wanze and Smarty. One thing I can not figure out is how to use pw's `__('…')` translate function within my templates.

This is how I tried:


<a href="{$page->httpUrl}">__("zurück")</a>
<a href="{$page->httpUrl}">{__("zurück")}</a>

I would expect to find `fundus-index.tpl` in translatable files. Unfortunately it does not show up even after refreshing the list (screenshot attached). 
When trying to enter the file directly I get a warning saying: ProcessLanguageTranslator: That file has no translatable phrases

After that I've tried to setup a new php file `/site/translations.php` with content `__("zurück")`. This file shows up and I can successfully translate the string which I would expect that this string is globally available across all files (missing knowledge regarding the usage of translations ;) However my template file does not care about this newly created translation.

So long story short. How can I use translations in smarty templates?

Best regards,


Bildschirmfoto 2020-04-12 um 22.17.03.png

  • Like 1
Link to comment
Share on other sites

10 hours ago, toni said:

this can be closed (cannot find a close button 😕 time to shut down the computer.)

Hey @toni!

There's no close action on the forum, but I'm going to merge this topic with the TemplateEngineFactory support board — the recommended approach is that if you have questions regarding specific module, you should post them on the support board for that module. You can find the correct board via the modules directory (there's a "support board" link in the sidebar for each module) 🙂

Link to comment
Share on other sites

  • 3 weeks later...
On 4/13/2020 at 8:57 AM, teppo said:

Hey @toni!

There's no close action on the forum, but I'm going to merge this topic with the TemplateEngineFactory support board — the recommended approach is that if you have questions regarding specific module, you should post them on the support board for that module. You can find the correct board via the modules directory (there's a "support board" link in the sidebar for each module) 🙂

Nice! Thank you @teppo

Link to comment
Share on other sites

  • 2 months later...
  • 1 month later...

Having a rough go with performance and figuring out how to diagnose issues. I noticed that as I was building out a template that the load times on my local dev environment continued to get slower and slower. Basically slower than browsing the internet. I recently picked up the Pro DevTools modules and started working from the Profiler and the results have been pretty bad. I'm using the Twig Template Engine.

It is taking ~1.5 seconds for the server to render the page before returning anything to the browser. I started to work backwards through my code and I cannot find where there would be issues that should be causing this much of a slowdown, I wasn't able to get speed differences by disabling modules and I don't think that I'm running anything that would conflict.

I went through my templates and partials and started commenting out loops. I have a few loops on the home page to render picture grids, a blog feed, and navigation in both the footer and the header. There aren't any calls to modules or special functions that are happening inside these loops. When studying the output of Profiler there's no indication that anything is booting up during the page rendering process either. By commenting out all of the loops it dropped the render time from ~1.5s to .3-.5s, which is still slow for ProcessWire. I've attached two screenshots of the Profiler output for comparison. Everything below the cutoff in the picture had zero execution time. I'm not experiencing any slowdown on other local sites.

Appreciate any help!

Currently running:
ProcessWire 3.0.164 Master
TemplateEngineFactory v2
TemplateEngineTwig v3
PHP 7.3.13




Link to comment
Share on other sites

  • 2 months later...

I'm trying to change template on the fly (when there is a urlSegment in homepage) and I'm almost there (I guess), the behaviour is strange, the markup is working but if I print the template name I get the home page, something is not working properly
The code is inside a custom module. Thanks for the help. I'm using v1 (can't use v2)

public function ready() {   
	$this->addHookBefore('Page::render', $this, 'hookProfiles');
protected function hookProfiles($event){
        $page = $event->object;
        if($page->template == 'home' && wire('input')->urlSegment1 != ''){
            $factory = $this->modules->get('TemplateEngineFactory');
            $theme   = $factory->load('author.tpl');
            wire()->set('view', $theme);
Link to comment
Share on other sites

  • 3 weeks later...

Hi! Does anyone know how to handle throwing a Wire404Exception so that PW renders the 404 page as it normally does?


Fatal Error: Uncaught Wire404Exception

I am using the Smarty Engine. Both the engine factory and smarty engines are on their latest versions. 

I am using url segments to change the url structure of the site I'm working on.

Doing something like this:

if($input->urlSegment1) {
   $pageOnSegment = getPageToRender(); 
   $view->set('page', $page);
} else{
   throw new Wire404Exception();


Link to comment
Share on other sites

Hi elabx,

On one of my sites, I have:

if ($input->urlSegment1){
  // unknown URL segment, send a 404
  throw new Wire404Exception();

and in another place I was using:

// Don't let search engines index non-existing pages
// see https://processwire.com/blog/posts/processwire-2.6.18-updates-pagination-and-seo/
// if(!count($paginated_calendar_postings) && $input->pageNum > 1) {
if(!count($paginated_calendar_postings) && $input->pageNum > 1) {

  // I'm not sure why this line is needed, but it is
  // $session->redirect($pages->get($config->http404PageID)->httpurl());
  throw new Wire404Exception();

I think I used to have to do this, before a bug was fixed in this module?


Hope that helps

Link to comment
Share on other sites

Hi @gmclelland! I did found the issues you came across, but didn't solve them and also the redirect shouldn't happen before the 404 😞

I read on this github issue that this shouldn't happen anymore in version 2 of the module so I went for updating everything but didn't work either still can't throw the exception on the controller. 

Link to comment
Share on other sites

Hmm... I'm not sure then.  Are you using TemplateEngineFactory with TemplateEngineTwig?  Did you upgrade TemplateEngineTwig as well?  Did you upgrade your Twig libraries with composer?  Did you clear your site caches with Modules > Refresh?  Just some thoughts...

If I remember right..after upgrading to 2.x

throw new Wire404Exception();

most of the time it would work, but one time it didn't.  I just can't remember the use case.  So maybe that bug isn't fully fixed?  Perhaps you can provide Wanze your code so he can replicate and fix the problem?

Link to comment
Share on other sites

  • 4 months later...

I am looking for an output strategy for repater fields or Repater Matrix fields (Pro fields) in my case.

I would like to replicate the approach Ryan described in the blog post https://processwire.com/blog/posts/more-repeaters-repeater-matrix-and-new-field-rendering/ , but using Template Engine Factory (because I want to use Smarty or another template language). 


In short: Instead of a foreach loop that then uses many if clauses to distinguish the type, I would like to have a separate controller and template for each repeater matrix item.
The controller should be used to modify the output before.

Here is my working code, but I wonder if it might be better to use hooks like Template Engine Factory's hookBeforePageRender, or something else?

$factory = $this->modules->get('TemplateEngineFactory');
// check if the actual page has a modules_repeater (Repeater Matrix field)
// and provide the output of the different modules as a variable
if ($this->page->hasField('modules_repeater')) {
  // now get the output based on the type
  foreach ($this->page->modules_repeater as $module) {
    // Get the controller, to render a repeater item.
    $controller = $factory->controller("modules_controllers/{$module->type}.php", "modules/{$module->type}.tpl");
    // You might pass some data via to the controller file, which you find at site/templates/modules_controller/nameOfTheRepeaterMatrixItem.
    // We assign the module repeater item to the $page variable so we can use it in our template and controller like this
    // $page->hero_headline
    $controller->page = $module;
    $output = $factory->render("modules/{$module->type}", ['page' => $module]);
    // Executing the controller renders the associated template via template engine.
    $this->view->set('modules_repeater', $output);

Any suggestions?

  • Like 1
Link to comment
Share on other sites

  • 2 months later...


Trying to use Pug templating engine and have downloaded and installed both TemplateEngineBase and pug module, however pug itself seems to be missing as the module throughs an error saying Phug isn't found. How should I install pug itself??

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...