Wanze

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!

Cheers

  • Like 4

Share this post


Link to post
Share on other sites

Hi,

I don't know whether anyone is actively monitoring the thread for the TemplateEngineTwig.module but I have posted the following message there. Many thanks! :)

 

Share this post


Link to post
Share on other sites

Hi

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

Besen

 

Share this post


Link to post
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...

Cheers

Share this post


Link to post
Share on other sites

Yeah it won't work sorry... so in this case my solution would be to use the same controller/template for your home page and special page. Still not sure if I understood you correctly though.

Share this post


Link to post
Share on other sites

Ok ! Then I found a simple and evident solution : I associated my template "special-page" on root 'Home' in Processwire back-office. It worked fine !

Thanks for your help and your pretty goode module :-)

  • Like 1

Share this post


Link to post
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.

Share this post


Link to post
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.

Cheers

  • Like 1

Share this post


Link to post
Share on other sites

Hello

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

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

// DETECT IF PORTFOLIO
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

Share this post


Link to post
Share on other sites

@Besen

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?

Share this post


Link to post
Share on other sites

@Wanze

Then I would like to use basic_page view template normally, but sometimes, if the page to display has got portfolio children I have to display these on a summary portfolio view.

Share this post


Link to post
Share on other sites

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

Eg:

$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!

Cheers

Share this post


Link to post
Share on other sites

Finaly I juste included _init.php just after $view = factory->load in my if test. It worked fine ;-)

Share this post


Link to post
Share on other sites

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

https://github.com/wanze/TemplateEngineFactory/issues/6

Quote

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

E.g.
my-tempalte/json.tpl
my-template/html.tpl

if($format == 'json') {
$view->setFilename('my-tempalte/json.tpl');
} else {
$view->setFilename('my-tempalte/html.tpl');
}

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?

 

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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/

Cheers

  • Like 1

Share this post


Link to post
Share on other sites

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: 
https://bitbucket.org/pwFoo/templatefilehelper/src/060a9f5129e6eca65c75885572aa0c23ed83e591/TemplateFileHelper.module?at=master&fileviewer=file-view-default

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.

Share this post


Link to post
Share on other sites

Some tests done, but I don't know if TemplateEngineFactory fits my needs (current page inside of the global layout, ajax friendly usage, layout / current page scripts and styles).

Share this post


Link to post
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,

Menz

 

Share this post


Link to post
Share on other sites

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;
}

Cheers

  • Like 1

Share this post


Link to post
Share on other sites

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

includes/_main.php

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

views/home.php

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

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

Share this post


Link to post
Share on other sites

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">
                  <h3>
                    <a href="{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a>
                  </h3>
                  <div class="meta">
                    <p>{% if post.editable() %}
                      <a href="{{ config.urls('admin') }}page/edit/?id={{ post.id }}">Edit</a>
                    {% endif %}
                    </p>
                  </div>

                  {% 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>
                    </div>
                  {% endif %}
                  
                </div><!-- card-section -->
              </article>
{% 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?

Share this post


Link to post
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 thomasaull
      Some time ago I created a site profile for creation of a REST API with ProcessWire. Since I kept struggeling with updating stuff between different projects which use this, I decided to convert it into a module. It is now ready for testing: https://github.com/thomasaull/RestApi
      Additionally I added a few small features:
      automatic creation of JWT Secret at module install routes can be flagged as auth: false, which makes them publicly accessible even though JWT Auth is activated in module settings To check things out, download and install the module and check the folder /site/api for examples.
      If you find any bugs or can think of improvements, please let me know!
    • By kongondo
      Sites Manager
       
      16 September 2018:
      FOR NOW, PLEASE DO NOT USE THIS MODULE IN A PRODUCTION SITE. A  RECENT ProcessWire UPDATE HAS BROKEN THE MODULE. I AM WORKING ON A FIX.
       
      ################
       
      Sites Manager is a module for ProcessWire that allows Superusers to easily create/install ProcessWire sites on the same serverspace the module is running in. Only Superusers can use the module. You can create both stand-alone and multi-sites.
       
      Single/Stand-alone Sites
      Stand-alone or single-sites are sites that will run in their own document root/directory with their own wire and site folders, .htaccess, index.php, etc. In other words, a normal ProcessWire site.
      Multiple Sites
      Multi-sites are sites that will run off one wire folder (shared amongst two or more sites) each having their own site folder and database. In this regard, it is important to note that Sites Manager is not in itself a multiple sites solution! Rather, it is a utility that helps you create multi-sites to be run using the ProcessWire core multiple sites feature. For more on this core feature, see the official ProcessWire documentation, specifically the solution referred to as Option #1.
      Option #1 approach requires the site admin to initially install ProcessWire in a temporary directory for each new site. The directory then needs to be renamed as site-xxx, where ‘xxx’ is any name you want to use to differentiate the installation from other sites, before it is moved to the webroot. For instance, site-mysite, site-another, site-whatever. In addition, the /wire/index.config.php file must be copied/moved to the webroot. Each time a site is added, the index.config.php has to be edited to add ‘domain’ => ‘site-directory’ key=>value pairs for the site. This process can become a bit tedious. This module aims to automate the whole multi-site site creation process.
      The module is based off the official ProcessWire installer. Creating a site is as simple as completing and submitting a single form! You also have the option to type and paste values or reuse a pre-defined install configuration.
       
      The module will:
      Install a ProcessWire site in your named directory, applying chmod values as specified
      Move the directory to your webroot
      Update/Create a Superuser account as per the submitted form, including setting the desired admin theme and colour
      For multi sites, update sites.json (used by index.config.php to get array of installed sites)
       
      For multi sites, the only difference in relation to the core multi-sites index.config.php is that this file is slightly different from the one that ships with ProcessWire.
      Download from GitHub: Sites Manager (Beta Release)
      Features
      Install unlimited number of sites in one (multi-sites) or independent (single-site) ProcessWire installs. Install by completing a Form, Typing or pasting in configurations or using pre-created install configurations. Choose an Admin Theme to auto-install along with the site installation. For single-sites installation, download, save and reuse ProcessWire versions of your choice. Install and maintain site profiles for reuse to create other sites. Create install configurations to speed up installation tasks. Client and server-side validation of site creation values. Edit uploaded profiles (e.g., replace profile file). Lock installed sites, configurations and profiles to prevent editing. Bulk delete items such as site profiles, installed site directories and/or databases (confirmation required for latter two). View important site details (admin login, chmod, etc). Links to installed sites home and admin pages. Timezones auto-complete/-suggest. Pre-requisites, Installation & Usage
      Please see the documentation.
      Technicalities/Issues
      Only Superusers can use the module.
      ProcessWire 2.7 - 3.x compatible
      Currently using ProcessWire 2.7 installer (install.php)
      For multi-sites, potential race condition when sites.json is being updated on a new site install vs. index.config.php accessing the json file?
      Not tested with sub-directory installs (for instance localhost/pw/my-site-here/)
      Currently not doing the extra/experimental database stuff (database charset and engine)
      Future Possibilities
      Install specified modules along with the ProcessWire install
      Profile previews?
      Credits
      @ryan: for the ProcessWire installer
      @abdus: for the index.config.php reading from JSON idea
      @swampmusic: for the challenge
      Video Demo
      Demo  showing how quick module works on a remote server [YMMV!]. Video shows downloading and processing two versions of ProcessWire (~takes 7 seconds) and installing a single/stand-alone ProcessWire 3 site using the new Admin Theme UI Kit (~2 seconds) on a remote server.
       
      Screens
      1

      2

       
       
    • By Robin S
      Breadcrumb Dropdowns
      Adds dropdown menus of page edit links to the breadcrumbs in Page Edit.

      Installation
      Install the Breadcrumb Dropdowns module. The module requires ProcessWire >= v3.0.83 and AdminThemeUikit.
      There is a checkbox option in the module config that determines if the breadcrumb dropdowns will include pages that the user does not have permission to edit.
      Features/details
      The module adds an additional breadcrumb item at the end for the currently edited page. That's because I think it's more intuitive for the dropdown under each breadcrumb item to show the item's sibling pages rather than the item's child pages. In the dropdown menus the current page and the current page's parents are highlighted in a crimson colour to make it easier to quickly locate them in case you want to edit the next or previous sibling page. Unpublished and hidden pages are indicated in the dropdowns with similar styling to that used in Page List. If the option to include uneditable pages is selected then those pages are indicated by italics with a reduced text opacity and the "not-allowed" cursor is shown on hover. There is a limit of 25 pages per dropdown for performance reasons and to avoid the dropdown becoming unwieldy. If the current user is allowed to add new pages under the parent page an "Add New" link is shown at the bottom of the breadcrumb dropdown. If the currently edited page has children or the user may add children, a caret at the end of the breadcrumbs reveals a dropdown of up to the first 25 children and/or an "Add New" link. Overriding the listed siblings for a page
      If you want to override the siblings that are listed in the dropdowns you can hook the BreadcrumbDropdowns::getSiblingsmethod and change the returned PageArray. For most use cases this won't be necessary.
      Incompatibilities
      This module replaces the AdminThemeUikit::renderBreadcrumbs method so will potentially be incompatible with other modules that hook the same method.
       
      https://modules.processwire.com/modules/breadcrumb-dropdowns/
      https://github.com/Toutouwai/BreadcrumbDropdowns
    • By bernhard
      Some of you might have followed the development of this module here: https://processwire.com/talk/topic/15524-previewdiscussion-rockdatatables/ . It is the successor of "RockDataTables" and requires RockFinder to get the data for the grid easily and efficiently. It uses the open source part of agGrid for grid rendering.
       
      WHY?
      ProcessWire is awesome for creating all kinds of custom backend applications, but where it is not so awesome in my opinion is when it comes to listing this data. Of course we have the built in page lister and we have ListerPro, but none of that solutions is capable of properly displaying large amounts of data, for example lists of revenues, aggregations, quick and easy sorts by the user, instant filter and those kind of features. RockGrid to the rescue 😉 
       
      Features/Highlights:
      100k+ rows Instant (client side) filter, search, sort (different sort based on data type, eg "lower/greater than" for numbers, "contains" for strings) extendable via plugins (available plugins at the moment: fullscreen, csv export, reload, batch-processing of data, column sum/statistics, row selection) all the agGrid features (cell renderers, cell styling, pagination, column grouping etc) vanilla javascript, backend and frontend support (though not all plugins are working on the frontend yet and I don't plan to support it as long as I don't need it myself)  
      Limitations:
      While there is an option to retrieve data via AJAX the actual processing of the grid (displaying, filtering, sorting) is done on the client side, meaning that you can get into troubles when handling really large datasets of several thousands of rows. agGrid should be one of the most performant grid options in the world (see the official example page with a 100k row example) and does a lot to prevent problems (such as virtual row rendering), but you should always have this limitation in mind as this is a major difference to the available lister options that do not have this limitation.
      Currently it only supports AdminThemeUikit and I don't plan to support any other admin theme.
       
      Download: https://gitlab.com/baumrock/FieldtypeRockGrid
      Installation: https://gitlab.com/baumrock/RockGrid/wikis/Installation
      Quikckstart: https://gitlab.com/baumrock/RockGrid/wikis/quickstart
      Further instructions: https://gitlab.com/baumrock/RockGrid/wikis/quickstart#further-instructions
      Changelog: https://gitlab.com/baumrock/FieldtypeRockGrid/raw/master/changelog.md
       
      Module status: alpha, License: MIT
      Note that every installation and uninstallation sends an anonymous google analytics event to my google analytics account. If you don't want that feel free to remove the appropriate lines of code before installation/uninstallation.
       
      Contribute:
      You can contribute to the development of this and other modules or just say thank you by
      testing, reporting issues and making PRs at gitlab liking this post buying me a drink: paypal.me/baumrock/5 liking my facebook page: facebook.com/baumrock hiring me for pw work: baumrock.com  
      Support: Please note that this module might not be as easy and plug&play as many other modules. It needs a good understanding of agGrid (and JavaScript in general) and it likely needs some looks into the code to get all the options. Please understand that I can not provide free support for every request here in the forum. I try to answer all questions that might also help others or that might improve the module but for individual requests I offer paid support for 60€ per hour (excl vat).
       
      Use Cases / Examples:
      Colored grid cells, Icons, Links etc. The Grid also has a "batcher" feature built in that helps communicating with the server via AJAX and managing resource intensive tasks in batches:

      Filters, PW panel links and instant reload on panel close:

      You can combine the grid with a chart library like I did with the (outdated) RockDataTables module:

    • By Ken Muldrew
      I'm trying to get a short routine to run once per day that will look at some pages and send a reminder email when that customer's subscription (yearly) is about to expire. When I run the code in a template then it works without issue, but inside my lazycron service routine, I get an "Error: Uncaught Error: Call to a member function get() on null" as if the database cannot be found. My autoload module is just the sample HelloWorld module included with ProcessWire, editted to perform this task. The whole of it is included below (I've stripped out the code that generates the email because it never gets past $pages->find):
       
      <?php namespace ProcessWire;
      /**
       * ProcessWire 'LazyCronLoad'  module
       *
       */
      class LazyCronLoad extends WireData implements Module {
          public static function getModuleInfo() {
              return array(
                  'title' => 'LazyCronLoad', 
                  'version' => 1, 
                  'summary' => 'Just loads a lazy cron callback.',
                  'singular' => true, 
                  'autoload' => true, 
                  );
          }
          public function init() {
              // initialize the hook in the AutoLoad module
              $this->addHook('LazyCron::everyDay', $this, 'myHook');
              
          }
          public function myHook(HookEvent $e) {
              // called once per day
              wire('log')->save('user_activities',' lazy cron service routine');
                  $transport_pages = $pages->find("template=aggregate-entry, aggregate_type.title='Transport'");
                  foreach ($transport_pages as $page) {
                      if (($page->purchase_date + 30325800 < time()) && ($page->purchase_date + 30412600 > time())) { // between 351 and 352 days
                          wire('log')->save('user_activities', $page->id . ' email reminder sent');
                          // send email
                  }
              }
          }        
          
      }
      The first wire('log') shows up but the second one doesn't (the purchase_date condition is met (as demonstrated by running the code in a template close in time to when the lazycron routine executes)). The error log gives the Uncaught Error shown above. 
      I think this is a beginner's mistake with something obvious being missed and would be grateful for any assistance in fixing it.