Jump to content

Module: Twig for the TemplateEngineFactory


Wanze
 Share

Recommended Posts

I am trying to setup my controllers and views like eangulo@spiria, so:

/templates
      /controllers
          home.php
          basic-page.php
      /views
          home.twig
          basic-page.twig

In the module "Template Engine ProcessWire" I have set up "path to templates: templates/controllers/". But ProcessWire doesn't find for example the home.php template. I get 404 Page not found error if I try to access it in the front-end. If I move home.php to "templates/" then twig works.


Last thing...how do I use the "Global template file" that I find in both "Template Engine ProcessWire" and "ModulesTemplate Engine Twig"? What is that used for?

Link to comment
Share on other sites

On 27/07/2016 at 6:54 PM, Gazley said:

@Manaus

That's great! Here is my hooked method:


    public function hookInitTwig(HookEvent $event)
    {

        $twig = $event->arguments('twig');
        $twig->addGlobal('hsaApp', wire('config')->hsaApp);
        $twig->addGlobal('hsaDist', wire('config')->hsaDist);
        $twig->addExtension(new \Twig_Extension_Debug());

    }

The only problem with what you have done is that you have amended the original module. When you update that module, you will lose your added code. If you add to a hooked method outside of the Twig module, your changes will be preserved.

@Gazley I am a total noob, in which file do I add that snippet of code? In home.php?

Link to comment
Share on other sites

11 hours ago, microcipcip said:

In the module "Template Engine ProcessWire" I have set up "path to templates: templates/controllers/". But ProcessWire doesn't find for example the home.php template. I get 404 Page not found error if I try to access it in the front-end. If I move home.php to "templates/" then twig works.

Your "controllers" aka regular ProcessWire templates are always in "site/templates", you can't customize this path. However, with this setting, you tell the module where your twig templates are, e.g. "views" in your case.

11 hours ago, microcipcip said:

Last thing...how do I use the "Global template file" that I find in both "Template Engine ProcessWire" and "ModulesTemplate Engine Twig"? What is that used for?

Since you use twig, check out the template inheritance support from Twig, where you define a "global" template and other children-templates inherit stuff from it. If you enable this setting, you always have the same twig template behind the $view API variable.

10 hours ago, microcipcip said:

I am a total noob, in which file do I add that snippet of code? In home.php?

You either need to write this in an autoload module or attach the hook in your site/ready.php file. Learn more about hooks here: http://processwire.com/api/hooks/

Cheers

  • Like 2
Link to comment
Share on other sites

@Wanze I am still confused about the snippet of code for enabling dump(), I guess this function needs a class to be attached to, where do I add it?

Edit: I have enabled it with the following code (in init.php)
 

wire()->addHookAfter("TemplateEngineTwig::initTwig", function($event) {
  $twig = $event->arguments('twig');
  $twig->addGlobal('hsaApp', wire('config')->hsaApp);
  $twig->addGlobal('hsaDist', wire('config')->hsaDist);
  $twig->addExtension(new \Twig_Extension_Debug());
});

Do you happen to know why `{{ dump(page) }}` results in a empty white page but for example `{{ dump(page.title) }}` works?
Edit2: you need to install xdebug on php.ini :P

  • Like 1
Link to comment
Share on other sites

wire()->addHook("TemplateEngineTwig::initTwig", function($event) {
	$twig = $event->arguments('twig');
	$filter = new \Twig_SimpleFilter('age', function ($date) {
        return "50";
    });
	$twig->addFilter($filter);
});

I cannot figure out why my filter "age" is not recognized in my templates?

This code is at the top of my template's .php file. I've also tried putting it in my ready.php file. Neither one adds the "age" filter to twig...

 

 

Link to comment
Share on other sites

Does anybody know why I have to add the following code to every twig template?

{# FileCompiler=0 #}

If I remove that line, I get Parse Error: syntax error, unexpected ','

I am also having a difficult time debugging in php. Echo or print_r from within my template.php files usually result in php errors. What is the best practice to debug from php when Twig is enabled?

Link to comment
Share on other sites

@microcipcip

What is the extension for your twig template files, .html? Unless set in the site/config.php file, ProcessWire's FileCompiler should not compile .html files. I'll look into it and try to find a way to disable the compiling in the module itself.

 

Link to comment
Share on other sites

18 hours ago, Wanze said:

@microcipcip

What is the extension for your twig template files, .html? Unless set in the site/config.php file, ProcessWire's FileCompiler should not compile .html files. I'll look into it and try to find a way to disable the compiling in the module itself.

 

I use extension .twig, it is easier to highlight in the editor. Thanks a lot for looking into this :)

Link to comment
Share on other sites

  • 4 weeks later...

@microcipcip @eangulo@spiria

I pushed a potential fix to the dev branch of this module which should fix the errors with compiled templates. If anyone has the time to test it out, here's what you need to do:

  1. Get the newest version of the dev branch of ProcessWire
  2. Get the newest version of the dev branch of this module
  3. Delete your FileCompiler = 0 comments in the twig templates
  4. (maybe) Delete all files under /site/assets/cache/FileCompiler

It's hard to test for me, as I never got such errors - I think it depends on the content of your twig templates. However, I'm positive since there were no longer twig templates compiled in the cache of the FileCompiler.

I hope it works! :)

Cheers

  • Like 1
Link to comment
Share on other sites

On 2.11.2016 at 7:25 PM, rastographics said:

wire()->addHook("TemplateEngineTwig::initTwig", function($event) {
	$twig = $event->arguments('twig');
	$filter = new \Twig_SimpleFilter('age', function ($date) {
        return "50";
    });
	$twig->addFilter($filter);
});

I cannot figure out why my filter "age" is not recognized in my templates?

This code is at the top of my template's .php file. I've also tried putting it in my ready.php file. Neither one adds the "age" filter to twig...

 

 

You need to use addHookAfter instead of addHook, hope this helps!

Cheers

Link to comment
Share on other sites

On 05/12/2016 at 9:50 PM, Wanze said:

@microcipcip @eangulo@spiria

I pushed a potential fix to the dev branch of this module which should fix the errors with compiled templates. If anyone has the time to test it out, here's what you need to do:

  1. Get the newest version of the dev branch of ProcessWire
  2. Get the newest version of the dev branch of this module
  3. Delete your FileCompiler = 0 comments in the twig templates
  4. (maybe) Delete all files under /site/assets/cache/FileCompiler

It's hard to test for me, as I never got such errors - I think it depends on the content of your twig templates. However, I'm positive since there were no longer twig templates compiled in the cache of the FileCompiler.

I hope it works! :)

Cheers

@Wanze thanks a lot, it works with the dev branch of PW. Is this the one that is usually released on Fridays?

Link to comment
Share on other sites

Hello,

I'm new to this.  Can anyone tell me how to use a different Twig template when ajax is used?  In some cases you only want the content without the header and footer.  In other ajax cases you might want the content encoded as json.  I'm not sure how to achieve this.

if ($config->ajax) {...}

By the way for anyone else wondering:

  • This module works with PW3.
  • To get the Twig dump function you will need https://github.com/justb3a/processwire-twigextensions and $config->debug = true; in your site's config.php file.
  • You can use a _init.php to globally set twig variables for your templates.  Just set $config->prependTemplateFile = '_init.php'; in your config.php and then $view->set('headline', $page->title);  In your view's twig file you can print the variable with {{ headline}}
Link to comment
Share on other sites

 

Quote

In latte I can set which layout to use, isn't there a similar thing in twig?

Yes, in your view's .twig file there is {% extends './partials/base.html.twig' %}

Maybe in my view's .twig file I can just do the following?

if ($config->ajax) {
  {# Load without header and footer #}
  {% extends './partials/ajax.twig' %}
} else {
  {# Load with header and footer #}
  {% extends './partials/base.html.twig' %}
}

Or, maybe I need something like what is posted at:

Anyways, I would still like to hear how other people are using this module with Ajax.

 

 

Link to comment
Share on other sites

On 16.12.2016 at 7:46 PM, gmclelland said:

Hello,

I'm new to this.  Can anyone tell me how to use a different Twig template when ajax is used?  In some cases you only want the content without the header and footer.  In other ajax cases you might want the content encoded as json.  I'm not sure how to achieve this.

if ($config->ajax) {...}

By the way for anyone else wondering:

  • This module works with PW3.
  • To get the Twig dump function you will need https://github.com/justb3a/processwire-twigextensions and $config->debug = true; in your site's config.php file.
  • You can use a _init.php to globally set twig variables for your templates.  Just set $config->prependTemplateFile = '_init.php'; in your config.php and then $view->set('headline', $page->title);  In your view's twig file you can print the variable with {{ headline}}

Hi,

There are different solutions to do this. You could check in your Controller (ProcessWire-Template)  if the request is ajax and pass a variable to twig, if a header/footer should be rendered:

// In controller:
$showHeader = true;
if ($config->ajax) $showHeader = false;
$view->showHeader = $showHeader;

// In your template (sorry I don't know the exact twig syntax) :)
{% if showHeader %}

{% endif %}

Or, if you have enabled that ProcessWire API variables are available in your twig templates, you should be able to use $config directly in twig

I usually create partial views if I need to output some content multiple times in different context:

// In your controller
if ($config->ajax) {
  $partial = $factory->load('partials/my-page-ajax');
  $partial->page = $page;
  echo $partial->render();
  exit();
}

As @microcipcip mentioned, you could also make use of urlSegments or plain GET variables to output HTML or JSON based on the urlSegment/GET variable.

Cheers

Link to comment
Share on other sites

I have a few more questions because I'm stuck :(

1.  I need to install http://twig.sensiolabs.org/doc/extensions/index.html#extensions-install so I can use the truncate filter, but when I go to my site root and run composer require twig/extensions it will also load the latest version of twig as a dependency.  This dependency conflicts with the version included in the TemplateEngineTwig module.  Should twig be removed from the module and managed via composer only?  If I then comment out the autoloader in TemplateEngineTwig module so that PW3 can just load twig from the site's vendor directory, I get the following Error: Exception: Unknown "truncate" filter.

2.  Is the __() functions recognized?  I get Error: Exception: Unknown "__" function when I try to use it.

3.  If would be helpful if you can add documentation to module's readme.txt on how to load additional twig extensions, macros, filters?

Thank you for any help you can provide.

Link to comment
Share on other sites

@gmclelland

I try to answer the questions in the same order as your questions:

  1. The module offers a hook which can be used to customize all twig objects returned by the factory, TemplateEngineTwig::initTwig(). I'm not sure if you're familiar with how ProcessWire's hooking system works? There is a module from @justb3a which adds some extensions to twig: https://github.com/justb3a/processwire-twigextensions. The extensions are also loaded via composer inside the module's folder, not on the root level. I suggest to take a look how this module works and then customize it in order to fit your needs.
  2. No, you would need to register a function in twig which takes care of outputting translated strings. A simple solution would be to translate the strings in your controller and pass them to twig.
  3. Yep I definitely should do that! :)

Merry Christmas! :lol:

Link to comment
Share on other sites

I read up on latte and liked it, but Twig is so widely used in other CMS systems like Grav, Drupal 8, CraftCms, Bolt.Cm and others.  It seemed better to invest my time learning something a bit more portable.

Thank you for the suggestion though.

I also like the Tracy debugger module. I haven't tried yet, but I wonder if that can be used with twig somehow?

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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...