Jump to content
tpr

Module: Template Latte Replace

Recommended Posts

v029 is available:

  • change in adding custom macros and filters: $view->addMacro(), $view->addFilter()
  • added $view->invokeFilter($name, $args) method to run filters directly in PHP
  • updated filters to accept PageArrays instead selectors only
  • new filter: 'renderpager'
  • new filter: 'getsetting' (to use with TextformatterMultivalue module)
  • $view->latte returns the Latte object
  • lowercase filter names

See the docs for "renderpager" filter, otherwise these changes won't affect you if you're not using your own custom filters/macros. Another goodie is the ability to run a filter directly in your PHP files (ready.php or template files).

  • Like 1

Share this post


Link to post
Share on other sites

Hey @tpr,

Thanks for your effort with this module! I haven't use this module and still stuck with the old way of setting up the latte template engine. Hopefully I got a chance to use your module moving forward.

Thanks!

  • Like 1

Share this post


Link to post
Share on other sites

Thanks! The old method is better to forget, the module is the way to go. The latest filters and latte-only template files make templating even more enjoyable. Recently I updated an earlier site of mine and I could throw off about half of the template files and the code is also much cleaner/maintainable.

  • Like 2

Share this post


Link to post
Share on other sites
2 hours ago, tpr said:

Thanks! The old method is better to forget, the module is the way to go. The latest filters and latte-only template files make templating even more enjoyable. Recently I updated an earlier site of mine and I could throw off about half of the template files and the code is also much cleaner/maintainable.

 

On my current project I decided to keep the .php extension but on the next one I'll enjoy this new approach for sure. Many thanks, @tpr !

Share this post


Link to post
Share on other sites

I like this approach because of less number of template files. Sometimes I end up with 10+ templates and it gets duplicated because of the view files. Keep in mind that you should use ready.php (or another one) to act as a controller if you still need to separate concerns. There you can use conditionals to target the current template or even include another php files if needed - I often include files eg. in case of the search template to keep ready.php less crowded.

Share this post


Link to post
Share on other sites

Just added a new filter 'default' (v031) - this seems to be a nice shortcut for simple if-else conditions.

<div>
    {$page->product_description|default:'No description is available for this product.'}
</div>

I guess the core PW API could also use something like this:

$page->get('product_description', 'No description is available for this product.')

What do you think?

Share this post


Link to post
Share on other sites
7 minutes ago, tpr said:

I guess the core PW API could also use something like this:


$page->get('product_description', 'No description is available for this product.')

What do you think?

There is this:

<div>
    <?= $page->product_description ?: 'No description is available for this product.' ?>
</div>

 

  • Like 1

Share this post


Link to post
Share on other sites

Thanks, good suggestion, I haven't thought about this. Although for newbies it can be harder to understand.

It works in Latte too but I'll keep the 'default' filter as it's easier to use, especially when chaining filters:

{($page->title|replace:'Home','') ?: 'No content available.'}
{$page->title|replace:'Home',''|default:'No content available.'}

 

Share this post


Link to post
Share on other sites

v033 is available that contains two new filters, lazy and surround.

I like the succinctness of the surround filter, eg in case of a tag list:

{$p->tags->sort('name')->title()|surround:'li'|surround:'ul class="tags"'|noescape}
<ul class="tags">
	<li>one</li>
	<li>two</li>
	<li>three</li>
</ul>

The docs were moved to GitHub Wiki, the increasing number of filters required this.

  • Like 2

Share this post


Link to post
Share on other sites

Another filter added in v036: embediframe. Unlike other responsive embed setups this one uses two wrappers to allow setting custom width so the iframe won't necessarily fill the available horizontal space.

There's also a protectemail filter available and the bodyclass filter was updated to include paginated pages too.

  • Like 1

Share this post


Link to post
Share on other sites

Hi @tpr,

Have a question here (more like a Latte question rather than module question): I have my default base layout called @layout.latte which is a base template for almost all of my pages but I also want to have another layout template that does have a sidebar. How do I setup this up in such a way I only declare my base HTML file once? Using {extends} or {layout} directive seems to replace the whole template file? or am I missing something here?

Share this post


Link to post
Share on other sites

@peterfoeng - I'm not sure about Latte (tpr might be able to answer this better), but surely you can have one layout extend another? So you would have a base layout and a sidebar layout where the sidebar layout extends the base layout, which would import the content of the sidebar layout if it's provided. Blade provides a nice way of doing this by using a combination of @section() and @parent.

 

Share this post


Link to post
Share on other sites
10 minutes ago, Mike Rockett said:

@peterfoeng - I'm not sure about Latte (tpr might be able to answer this better), but surely you can have one layout extend another? So you would have a base layout and a sidebar layout where the sidebar layout extends the base layout, which would import the content of the sidebar layout if it's provided. Blade provides a nice way of doing this by using a combination of @section() and @parent.

 

My previous setup is not using this module and seems to be working ok (I am pretty sure I am just missing something here)

This is my previous setup:
I have `@base.latte` file which contains the default markup then on my `Contact Page` (where I want this page have to have a sidebar) I have the following markup:

`Contact.latte` file:

{extends '@layout.sidebar.latte'}

{block side_navigation}
  {include $config->paths->templates . 'views/components/_globals/side-navigation/contact.latte'}
{/block}

{block content}
....My content
{/block}

 

`@layout.sidebar.latte`file:

{extends '@base.latte'}

{block body}
  {var $fixed = in_array($page->template, array("Contact", "Size-Guide", "Product-Information"))}

  <main class="component component--main-content" id="content">
    <div class="component__wrapper">

      <div class="main-content">
        <div class="main-content__wrapper">
          <div class="main-content__col main-content__col--sidebar {if $fixed}main-content__col--sidebar-fixed{/if}">
            {block side_navigation}{/block}
          </div>
          <div class="main-content__col main-content__col--body">
            {include content}
          </div>
        </div>
      </div>

    </div>
  </main>
{/block}

This works with my previous setup. Hopefully @tpr can help a bit with his knowledge of this templating engine :)

Cheers

Share this post


Link to post
Share on other sites

What is the error you got? Layout inheritance is available in latte too.

btw you don't need separate layout for a sidebar, just add an empty block to the base layout and fill with markup when you need it.

Plus you don't need to pass the full path for includes, use relative paths, eg include 'components/...latte'.

Share this post


Link to post
Share on other sites

This is how I use multiple layouts in a project.

@default.latte:

...
<body>
{include content}
</body>
...

@sidebar-left.latte:

{layout '@default.latte'}

{block content}
    <div>
        <div class="main">
            {include main}
        </div>
        <div class="sidebar-left">
            {include sidebar_left}
        </div>
    </div>
{/block}

contact.latte:

{layout 'layouts/@sidebar-left.latte'}

{block sidebar_left}
    ...
{/block}

{block main}
    ...
{/block}

Maybe there's a better setup for this, please share if you find one :)

Share this post


Link to post
Share on other sites
12 hours ago, tpr said:

This is how I use multiple layouts in a project.

@default.latte:


...
<body>
{include content}
</body>
...

@sidebar-left.latte:


{layout '@default.latte'}

{block content}
    <div>
        <div class="main">
            {include main}
        </div>
        <div class="sidebar-left">
            {include sidebar_left}
        </div>
    </div>
{/block}

contact.latte:


{layout 'layouts/@sidebar-left.latte'}

{block sidebar_left}
    ...
{/block}

{block main}
    ...
{/block}

Maybe there's a better setup for this, please share if you find one :)

You're the man!!! benggg....problem solved

  • Like 1

Share this post


Link to post
Share on other sites

Hey @tpr,

How do you setup a page that returns just json response without the base layout template markup? I know we can set $view->json_encode = true but the template markup is also encoded, how do we avoid this?

Thanks for your help in advanced!

Share this post


Link to post
Share on other sites

Just create an empty layout, eg. @empty.latte:

{include content}

and of course tell the view file to use this layout:

{layout '../layouts/@empty.latte'}
{block content}
    ...
{/block}

 

Share this post


Link to post
Share on other sites

Two new macros in v038: minify and editlink.

Minify is an easy way to remove unnecessary whitespace and optionally to try some additional tweaks too. It's nowhere to ProCache or AIOM but can help reducing markup size. I could tweak things on one site to achieve 100% HTML minification according to gtmetrix but that required extra work on the markup so this macro alone won't help you on this :) 

As a bonus the macro can be used to remove whitespace between list items (<li>'s) which sometimes can cause headaches.

Editlink is another helper that can substitute bigger modules like FEEL, Fredi or the built-in frontend editor. There's nothing special in it, just outputs edit links to edit the page in the admin. First I was about to modify FEEL but I realized this would be more fun :) 

  • Like 2

Share this post


Link to post
Share on other sites

I've modified the editlink macro in v039, now you can easily add any attributes and additional url parameters to the edit link. This way it's easy to add edit links that open the admin in a lightbox. I've added a few lines about it to the docs along with a style example.

  • Like 3

Share this post


Link to post
Share on other sites

v041 contains two new filters: getlines and imageattrs.

The first is a simple replacement to my MultiValueTextformatter module. Unlike the module it can only return a simple or an associative array but in fact that's just enough most of the time.

The imageattrs filter is an easy way of adding image width-height-alt attributes. "alt" value is taken from image description or set empty if not provided, or optionally can be removed entirely.

  • Like 1

Share this post


Link to post
Share on other sites

Just popped in to praise the getlines filter's coolness :) I have a CKEditor field containing a simple unordered list. I wanted to animate each lines separately but it wasn't possible because the whole UL was rendered together so I couldn't add the required classes to each LI's.

Using getlines together with striptags filter it's now possible ($iterator is built-in):

<ul n:inner-foreach="($p->body|striptags|getlines) as $key => $value">
  <li data-animate data-animation-classes="animated fadeInLeft" data-animation-delay="{$iterator->counter * 300 + 200}">
    <h3>{$key}</h3> {$value}
  </li>
</ul>

Of course I could add the required attributes in CKEditor but that would require more troubles (modifying CKEditor field to allow attributes, hardcoded delay values, etc).

  • Like 3

Share this post


Link to post
Share on other sites

There was an undocumented "list" filter among the filters that is now "officially" published. It was similar to the built-in implode filter but didn't choke if you passed a string instead of an array to it. I suggested this improvement in the Nette forums but they weren't too enthusiastic. In PW there are times (at least I had) when you don't know for sure if a data is a string or an array so I added this check to avoid errors.

The filter removes empty values so no need to check data existence manually. You can specify a separator string and/or a HTML tag, so it's easy to build eg. an unordered list. Just apply it to an array of possible items and the filter will take care of the rest. Here is an example.

  • Like 1

Share this post


Link to post
Share on other sites

Just upgraded the module to v0.4.3. There's a new option to disable the "noescape" filter, and a workaround for translations on a non-multilanguage site.

The latter is a simple solution for a situation when you copy over a latte file from another project full with translations but the current project is single-language only. This is perhaps not an issue if you're using full strings for translation keys, e.g "_t('Read more')" instead "_t('read_more_text')" because the original key is returned. But even so you may start a non-English project and there you'll be in trouble :) I was there several times and ended up rewriting strings/translations all over the project, now they can remain in place and I have to add translations at one file (which you can copy over).

  • Like 1

Share this post


Link to post
Share on other sites

Just added a new 'getembedurl', 'append' and 'prepend' filters to v4.4.

With getembedurl you can retrieve the embed url to be used when embedding videos (currently for Youtube/Vimeo). Editors aren't really capable of copying the embed url so you can use this filter to allow them adding the url of the video to the admin.

Filters append and prepend are convenience filters that you can use to quickly append/remove data. Data can be primitive or arrays. These filters are particularly useful when chaining filters so you don't have to split the current line just to modify the original data.

The bodyclass filter now contains the name of the viewFile (if exists), prefixed with "v-", and directory separators converted to "-". Custom classes can be added using $page->body_class if needed.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      A community member raised a question and I thought a new sanitizer method for the purpose would be useful, hence...
      Sanitizer Transliterate
      Adds a transliterate method to $sanitizer that performs character replacements as defined in the module config. The default character replacements are based on the defaults from InputfieldPageName, but with uppercase characters included too.
      Usage
      Install the Sanitizer Transliterate module.
      Customise the character replacements in the module config as needed.
      Use the sanitizer on strings like so:
      $transliterated_string = $sanitizer->transliterate($string);
       
      https://github.com/Toutouwai/SanitizerTransliterate
      https://modules.processwire.com/modules/sanitizer-transliterate/
       
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version to 2.10, add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "http://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


    • By thomasaull
      I created a little helper module to trigger a CI pipeline when your website has been changed. It's quite simple and works like this: As soon as you save a page the module sets a Boolean via a pages save after hook. Once a day via LazyCron the module checks if the Boolean is set and sends a POST Request to a configurable Webhook URL.
      Some ideas to extend this:
      make request type configurable (GET, POST) make the module trigger at a specified time (probably only possible with a server cronjob) trigger manually Anything else? If there's interest, I might put in some more functionality. Let me know what you're interested in. Until then, maybe it is useful for a couple of people 🙂
      Github Repo: https://github.com/thomasaull/CiTrigger
    • By Robin S
      I created this module a while ago and never got around to publicising it, but it has been outed in the latest PW Weekly so here goes the support thread...
      Unique Image Variations
      Ensures that all ImageSizer options and focus settings affect image variation filenames.

      Background
      When using methods that produce image variations such as Pageimage::size(), ProcessWire includes some of the ImageSizer settings (height, width, cropping location, etc) in the variation filename. This is useful so that if you change these settings in your size() call a new variation is generated and you see this variation on the front-end.
      However, ProcessWire does not include several of the other ImageSizer settings in the variation filename:
      upscaling cropping, when set to false or a blank string interlace sharpening quality hidpi quality focus (whether any saved focus area for an image should affect cropping) focus data (the top/left/zoom data for the focus area) This means that if you change any of these settings, either in $config->imageSizerOptions or in an $options array passed to a method like size(), and you already have variations at the requested size/crop, then ProcessWire will not create new variations and will continue to serve the old variations. In other words you won't see the effect of your changed ImageSizer options on the front-end until you delete the old variations.
      Features
      The Unique Image Variations module ensures that any changes to ImageSizer options and any changes to the focus area made in Page Edit are reflected in the variation filename, so new variations will always be generated and displayed on the front-end.
      Installation
      Install the Unique Image Variations module.
      In the module config, set the ImageSizer options that you want to include in image variation filenames.
      Warnings
      Installing the module (and keeping one or more of the options selected in the module config) will cause all existing image variations to be regenerated the next time they are requested. If you have an existing website with a large number of images you may not want the performance impact of that. The module is perhaps best suited to new sites where image variations have not yet been generated.
      Similarly, if you change the module config settings on an existing site then all image variations will be regenerated the next time they are requested.
      If you think you might want to change an ImageSizer option in the future (I'm thinking here primarily of options such as interlace that are typically set in $config->imageSizerOptions) and would not want that change to cause existing image variations to be regenerated then best to not include that option in the module config after you first install the module.
       
      https://github.com/Toutouwai/UniqueImageVariations
      https://modules.processwire.com/modules/unique-image-variations/
    • By Sebi
      I've created a small module which lets you define a timestamp after which a page should be accessible. In addition you can define a timestamp when the release should end and the page should not be accessable any more.
      ProcessWire-Module: http://modules.processwire.com/modules/page-access-releasetime/
      Github: https://github.com/Sebiworld/PageAccessReleasetime
      Usage
      PageAccessReleasetime can be installed like every other module in ProcessWire. Check the following guide for detailed information: How-To Install or Uninstall Modules
      After that, you will find checkboxes for activating the releasetime-fields at the settings-tab of each page. You don't need to add the fields to your templates manually.
      Check e.g. the checkbox "Activate Releasetime from?" and fill in a date in the future. The page will not be accessable for your users until the given date is reached.
      If you have $config->pagefileSecure = true, the module will protect files of unreleased pages as well.
      How it works
      This module hooks into Page::viewable to prevent users to access unreleased pages:
      public function hookPageViewable($event) { $page = $event->object; $viewable = $event->return; if($viewable){ // If the page would be viewable, additionally check Releasetime and User-Permission $viewable = $this->canUserSee($page); } $event->return = $viewable; } To prevent access to the files of unreleased pages, we hook into Page::isPublic and ProcessPageView::sendFile.
      public function hookPageIsPublic($e) { $page = $e->object; if($e->return && $this->isReleaseTimeSet($page)) { $e->return = false; } } The site/assets/files/ directory of pages, which isPublic() returns false, will get a '-' as prefix. This indicates ProcessWire (with activated $config->pagefileSecure) to check the file's permissions via PHP before delivering it to the client.
      The check wether a not-public file should be accessable happens in ProcessPageView::sendFile. We throw an 404 Exception if the current user must not see the file.
      public function hookProcessPageViewSendFile($e) { $page = $e->arguments[0]; if(!$this->canUserSee($page)) { throw new Wire404Exception('File not found'); } } Additionally we hook into ProcessPageEdit::buildForm to add the PageAccessReleasetime fields to each page and move them to the settings tab.
      Limitations
      In the current version, releasetime-protected pages will appear in wire('pages')->find() queries. If you want to display a list of pages, where pages could be releasetime-protected, you should double-check with $page->viewable() wether the page can be accessed. $page->viewable() returns false, if the page is not released yet.
      If you have an idea how unreleased pages can be filtered out of ProcessWire selector queries, feel free to write an issue, comment or make a pull request!
×
×
  • Create New...