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 Soma
      LogMaintenance
      A simple ProcessWire module to give some maintenance control over log files. I found myself often having lots of log files for different things that can grow more or less quickly to a size where they can be difficult to maintain. The built in Logger of PW does a good job of giving you the possibility to delete or prune logs. But it has to be done manually and sometimes a log grows into millions of lines, which makes it often impossible to even prune it as it's too large.
      LogMaintenance uses LazyCron to run the maintenance task and there's several settings you can setup on a global or per log basis.
      Archive: will create zip files for each log file in logs/archive/ folder and add the log each time the maintenance is run to a subfolder containing the datetime.
      Lines: keeps logs to a certain number of lines 
      Days: keeps the log to a certain number of days
      Bytes: keeps the log to a certain amount of bytes
      Each setting is checked from top down, the first setting to contain something is used. So if you check the "Archive" option, all other settings are ignored and logs are archived everytime the LazyCron is executed. If you want to keep your logs to a certain amount of bytes just leave all other settings to 0 or blank.
      Per Log Settings
      There's a textarea that you can use to setup a config for a specific log file one per line. All the logs you define here ignore the global settings above. The syntax for the settings is:
      logname:[archive]:[lines]:[days]:[bytes] 
      errors:1:0:0:0 // would archive the errors log messages:0:10000:0:0 // will prune the errors log to 10000 lines  
      The module can be found on github for you to check out. It's still fresh and I'm currently testing.
      https://github.com/somatonic/LogMaintenance
    • By teppo
      Fieldtype Page IDs is a third party Fieldtype that, simply put, stores Page references as integers (Page IDs).
      This fieldtype was built as a quick and dirty workaround for Page Reference fields' inability handle self-references due to circular reference issues. A project I've been working on for a while now includes a combination of RepeaterMatrix content blocks and tagging/categorization system that would've resulted in a lot of duplicate pages (and plenty of unnecessary manual work for content editors) had I used built-in Page Reference fields, and thus a new Fieldtype felt like the most sensible approach.
      Fieldtype Page IDs was designed to be loosely compatible with Page References in order to make conversions between the two feasible, but it is quite limited feature wise:
      largely due to the fact that stored values are actually just integers with no connection to Pages whatsoever some advanced selectors and related features are not supported, and page values can't be directly accessed configuration settings are limited to the bare essentials (selector string and Inputfield class) only a handful of Inputfields (AsmSelect, Checkboxes, Text) are (currently) supported Anyway, in case you need to store Page IDs (and Page IDs only) and are happy with the limitations mentioned above, feel free to give this Fieldtype a try. It has been working fine for me in one particular project, but hasn't been tested that much, so please tread carefully – and let me know if you run into any issues.
      GitHub repository: https://github.com/teppokoivula/FieldtypePageIDs
      Modules directory: https://modules.processwire.com/modules/fieldtype-page-ids/
    • By daniels
      This is a lightweight alternative to other newsletter & newsletter-subscription modules.
      You can find the Module in the Modules directory and on Github
      It can subscribe, update, unsubscribe & delete a user in a list in Mailchimp with MailChimp API 3.0. It does not provide any forms or validation, so you can feel free to use your own. To protect your users, it does not save any user data in logs or sends them to an admin.
      This module fits your needs if you...
      ...use Mailchimp as your newsletter / email-automation tool ...want to let users subscribe to your newsletter on your website ...want to use your own form, validation and messages (with or without the wire forms) ...don't want any personal user data saved in any way in your ProcessWire environment (cf. EU data regulation terms) ...like to subscribe, update, unsubscribe or delete users to/from different lists ...like the Mailchimp UI for creating / sending / reviewing email campaigns *I have only tested it with PHP 7.x so far, so use on owners risk
      EDIT:
      I've updated the module to 0.0.4. I removed the instructions from this forum, so I don't have to maintain it on multiple places. Just checkout the readme on github 🙂
      If you have questions or like to contribute, just post a reply or create an issue or pr on github. 
    • By bernhard
      WHY?
      This module was built to fill the gap between simple $pages->find() operations and complex SQL queries.
      The problem with $pages->find() is that it loads all pages into memory and that can be a problem when querying multiple thousands of pages. Even $pages->findMany() loads all pages into memory and therefore is a lot slower than regular SQL.
      The problem with SQL on the other hand is, that the queries are quite complex to build. All fields are separate tables, some repeatable fields use multiple rows for their content that belong to only one single page, you always need to check for the page status (which is not necessary on regular find() operations and therefore nobody is used to that).
      In short: It is far too much work to efficiently and easily get an array of data based on PW pages and fields and I need that a lot for my RockGrid module to build all kinds of tabular data.

      Basic Usage

       
      Docs & Download
      https://modules.processwire.com/modules/rock-finder/
      https://gitlab.com/baumrock/RockFinder/tree/master
       
      Changelog
      180528, v1.0.4 add custom select statement option 180516 change sql query method, bump version to 1.0.0 180515 multilang bugfix 180513 beta release <180513 preview/discussion took place here: https://processwire.com/talk/topic/18983-rocksqlfinder-highly-efficient-and-flexible-sql-finder-module/
    • By blynx
      Hej,
      A module which helps including Photoswipe and brings some modules for rendering gallery markup. Feedback highly appreciated
      (Also pull requests are appreciated 😉 - have a new Job now and don't work a lot with ProcessWire anymore, yet, feel free to contact me here or on GitHub, Im'm still "online"!)

      Modules directory: http://modules.processwire.com/modules/markup-processwire-photoswipe
      .zip download: https://github.com/blynx/MarkupProcesswirePhotoswipe/archive/master.zip
      You can add a photoswipe enabled thumbnail gallery / lightbox to your site like this. Just pass an image field to the renderGallery method:
      <?php $pwpswp = $modules->get('Pwpswp'); echo $pwpswp->renderGallery($page->nicePictures); Options are provided like so:
      <?php $galleryOptions = [ 'imageResizerOptions' => [ 'size' => '500x500' 'quality' => 70, 'upscaling' => false, 'cropping' => false ], 'loresResizerOptions' => [ 'size' => '500x500' 'quality' => 20, 'upscaling' => false, 'cropping' => false ], 'pswpOptions' => (object) [ 'shareEl' => false, 'indexIndicatorSep' => ' von ', 'closeOnScroll' => false ] ]; echo $pswp->renderGallery($page->images, $galleryOptions); More info about all that is in the readme: https://github.com/blynx/MarkupProcesswirePhotoswipe
      What do you think? Any ideas, bugs, critique, requests?
      cheers
      Steffen