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 daniels
      General
      This is a lightweight alternative to other newsletter & newsletter-subscription modules.
      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 You can find it here: https://github.com/danielstieber/SubscribeToMailchimp
      Let me know what you think and if I should add it to the Modules Directory.
      Setup
      Log into your Mailchimp account and go to  Profile > Extras > API Keys. If you don't have an API Key, create a new one. Copy your API Key and paste it in the module settings (Processwire > Modules > Site > SubscribeToMailchimp). Back in Mailchimp, go to the list, where you want your new subscribers. Go to Settings > List name and defaults. Copy the List ID an paste it in to the module settings.
      Usage
      To use the module, you need to load it into your template:
      $mc = $modules->get("SubscribeToMailchimp"); Now you can pass an email address to the module and it will try to edit (if the user exists) or create a new subscriber in your list.
      $mc->subscribe('john.doe@example.com'); You can also pass a data array, to add additional info.
      $mc->subscribe('john.doe@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe']); You can even choose an alternative list, if you don't want this subscriber in your default list.
      $mc->subscribe('john.doe@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe'], 'abcdef1356'); // Subscribe to List ID abcdef1356 If you want to unsubscribe a user from a list, you can use the unsubscribe method.
      $mc->unsubscribe('john.doe@example.com'); // Unsubscribe john.doe@example.com from the default list $mc->unsubscribe('john.doe@example.com', 'abcdef1356'); // Unsubscribe john.doe@example.com from the list abcdef1356 If you want to permantly delete a user, you can call the delete method. Carefully, this step cannot be undone
      $mc->delete('john.doe@example.com'); // Permanently deletes john.doe@example.com from the default list $mc->delete('john.doe@example.com', 'abcdef1356'); // Permanently deletes john.doe@example.com from the list abcdef1356  
      Important Notes
      This module does not do any data validation. Use a sever-sided validation like Valitron Make sure that you have set up your fields in your Mailchimp list. You can do it at Settings > List fields and *|MERGE|* tags Example
      Example usage after a form is submitted on your page:
      // ... validation of form data $mc = $modules->get("SubscribeToMailchimp"); $email = $input->post->email; $subscriber = [ 'FNAME' => $input->post->firstname, 'LNAME' => $input->post->lastname, ]; $mc->subscribe($email, $subscriber);  
      Troubleshooting
      In case of trouble check your ProcessWire warning logs.
      I can't see the subscriber in the list
      If you have enabled double opt-in (it is enabled by default) you will not see the subscriber, until he confirmed the subscription in the email sent by Mailchimp
      I get an error in my ProccessWire warning logs
      Check if you have the right List ID and API Key. Check if you pass fields, that exist in your list. Check if you pass a valid email address. Go to Mailchimps Error Glossary for more Information
      How To Install
      Download the zip file at Github or clone directly the repo into your site/modules If you downloaded the zip file, extract it in your sites/modules directory. You might have to change the folders name to 'SubscribeToMailchimp'. Goto the modules admin page, click on refresh and install it  
      Changelog
      0.0.2
      Note: You can update safely from 0.0.1 without any changes in your code
      New Features
      Added 'Unsubscribe' method $mc->unsubscribe($email, $list = "") Added 'Delete' method $mc->delete($email, $list = "") Bug Fixes and compatibility changes
      Removed type declarations to be compatible with PHP 5.1+* (thanks to wbmnfktr) Other
      Changed the way, the base url for the api gets called *I have only tested it with PHP 7.x so far, so use on owners risk
    • By BitPoet
      As threatened in the Pub sub forum in the "What are you currently building?" thread, I've toyed around with Collabora CODE and built file editing capabilities for office documents (Libre-/OpenOffice formats and MS Office as well as a few really old file types) into a PW module.
      If you are running OwnCloud or NextCloud, you'll perhaps be familiar with the Collabora app for this purpose.
      LoolEditor
      Edit office files directly in ProcessWire
      Edit your docx, odt, pptx, xlsx or whatever office files you have stored in your file fields directly from ProcessWire's page editor. Upload, click the edit icon, make your changes and save. Can be enabled per field, even in template context.
      Currently supports opening and saving of office documents. Locking functionality is in development.
      See the README on GitHub for installation instructions. You should be reasonably experienced with configuring HTTPS and running docker images to get things set up quickly.
      Pull requests are welcome!
      Here is a short demonstration:

    • By Robin S
      An Images field allows you to:
      Rename images by clicking the filename in the edit panel or in list view. Replace images, keeping metadata and filename (when possible) by dropping a new image on the thumbnail in the edit panel. Introduced here. But neither of these things is possible in File fields, which prompted this module. The way that files are renamed or replaced in this module is not as slick as in the Images field but it gets the job done. The most time-consuming part was dealing with the UI differences of the core admin themes. @tpr, gives me even more respect for the work that must go into AdminOnSteroids.
      Most of the code to support the rename/replace features is already present in InputfieldFile - there is just no UI for it currently. So hopefully that means these features will be offered in the core soon and this module can become obsolete.
       
      Files Rename Replace
      Allows files to be renamed or replaced in Page Edit.

      Usage
      Install the Files Rename Replace module.
      If you want to limit the module to certain roles only, select the roles in the module config. If no roles are selected then any role may rename/replace files.
      In Page Edit, click "Rename/Replace" for a file...
      Rename
      Use the text input to edit the existing name (excluding file extension).
      Replace
      Use the "Replace with" select to choose a replacement file from the same field. On page save the file will be replaced with the file you selected. Metadata (description, tags) will be retained, and the filename also if the file extensions are the same.
      Tip: newly uploaded files will appear in the "Replace with" select after the page has been saved.
       
      https://github.com/Toutouwai/FilesRenameReplace
      http://modules.processwire.com/modules/files-rename-replace/
    • By d'Hinnisdaël
      So I decided to wade into module development and created a wrapper module around ImageOptim, a service that compresses and optimizes images in the cloud. ImageOptim currently handles JPG, PNG and GIF files and, depending on the settings you use, shaves off between 15% and 60% in filesize. Great for bandwidth and great for users, especially on mobile.
      This module handles the part of uploading images to ImageOptim via their official API, downloading the optimized version and storing it alongside the original image.
       

       
      Download & Info
      GitHub / Module directory / Readme / Usage
       
      Why ImageOptim?
      There are other image optimization services out there, some of them free, that have outstanding ProcessWire modules. A few things make ImageOptim the best tool for most of my customers: It's not free, i.e. it will probably be around for a while and offers support. However, it's cheaper than some of the bigger competitors like Cloudinary. And it does PNG compression better than any of the free services out there, especially those with alpha channels.
       
      Installation
      Install the module like any other ProcessWire module, by either copying the folder into your modules folder or installing it via the admin. See above for downloads links on GitHub and in the module directory.
       
      Requirements
      To be able to upload images to the service, allow_url_fopen must be set on the server. The module will abort installation if that's not the case.
      I have only tested the module on ProcessWire 3.x installations. I don't see why it shouldn't work in 2.x, if anyone wants to try it out and report back.
       
      ImageOptim account
      To compress images, you first need to sign up for an ImageOptim account. They offer free trials to try the service.
       
      Usage (manual optimization)
      Images can be optimized by calling the optimize() method on any image. You can pass an options array to set ImageOptim API parameters.
      $image->size(800,600)->optimize()->url $image->optimize(['quality' => 'low', 'dpr' => 2]) // Set quality to low and enable hi-dpi mode
      Automatic optimization
      The module also has an automatic mode that optimizes all image variations after resizing. This is the recommended way to use this module since it leaves the original image uncompressed, but optimizes all derivative images.
      $image->size(800,600)->url // nothing to do here; image is optimized automatically
      To change compression setting for single images, you can pass an options array along with the standard ImageResizer options. Passing false disables optimization.
      $image->size(800, 600, ['optimize' => 'medium']) $image->size(800, 600, ['optimize' => ['quality' => 'low', 'dpr' => 2]]) $image->size(800, 600, ['optimize' => false])
      For detailed usage instructions and all API parameters, see the usage instructions on GitHub.
       
      Filenames
      Optimized images will be suffixed, e.g. image.jpg becomes image.optim.jpg. You can configure the suffix in the module settings.
       
      Roadmap
      Asynchronous processing. Not really high on the list. Image variations need to be created anyway, so waiting a few seconds longer on first load is preferable to adding complexity to achieve async optimization. Optimize image variations created by other modules. CroppableImage comes to mind. I don't use any of these, so if somebody wants to help out and submit a pull request — all for it! Add a dedicated page in the setup menu with a dashboard and detailed statistics. ImageOptim's API is very barebones for now, so not sure if that's feasible or even necessary.
      Stability
      I've been using this module on production sites for some time now, without hiccups. If you do notice oddities, feel free to comment here or investigate and submit PRs.
    • By PWaddict
      Module for hiding pages for non-superusers.
      Download
      HidePages
      Requirements
      ProcessWire 3.x Changelog
      1.0.1 (31 March 2018)
      Module renamed to prevent confusion 1.0.0 (30 March 2018)
      Initial release