Jump to content
tpr

Module: Template Latte Replace

Recommended Posts

Template Latte Replace

Latte template engine support for ProcessWire

Having wrote about this one for a few times and now here it is. The readme is not complete but should give a solid starting point.

 
Feel free to ask if something's not clear.
 

https://github.com/rolandtoth/TemplateLatteReplace

Edited by owzim
added Latte link
  • Like 11

Share this post


Link to post
Share on other sites

Thanks! Keep in mind that it requires PW 3 because of the namespace. There' no specific reason to make it PW 3 only but currently I have no time to rewrite.

Just added two global functions t() and n() to make string translations easier (v0.12).

  • Like 2

Share this post


Link to post
Share on other sites

Hi @tpr!

First of all, thank you for this module! I decide to use it instead of jade-php on my current project.

The problem is, I can't get the translations on _string.php to work.

I was getting an error when using v0.12 and i just saw that you released to 0.14. I download it, the error is gone but the translation won't appear, only the default text.

I tried directly on the .latte:

{_'text to translate'}

And setting a $view->variable on the controller. 

Any hints? What am I missing?

EDIT: I'm using the latest PW dev

Thanks!

Share this post


Link to post
Share on other sites

And setting a $view->variable on the controller

You don't need to set any variable for translation. If you need to translate string in the controller, use "_t('Text to translate').

In .latte file you can use '_', '_t'.

I tried to replicate your issue, here are the steps (tried on 3.015 and 3.017 also):

1. Added "<p>{_'Text to translate'}</p>" into "home.latte" (one underscore). Text appearead in my home page fine, untranslated.

2. Added this to "_strings.php" - mind the double underscore here:

__('Text to translate')
3. In the admin language editor I added the corresponding translation. Prevously I have selected the file "_strings.php" to translate.
etalsnart ot txeT
After that, this translated text appeared on the page. Even for the default language when setting it another value in the Language Translator.

My further bugsolving thoughts are:

  • are you sure the same string is in _strings.php and your .latte file?
  • try clearing Latte cache in module settings

Btw, just realized that _strings.php doesn't need starting php tag and comments but only listing the translations (without semicolon at the end).

  • Like 1

Share this post


Link to post
Share on other sites

Well, I installed a fresh copy of 3.0.17 and started all the steps again.

At the first moment, it didn't work, but after I changed the lines on _strings.php to 

  • _x('Text to translate', 'General');

instead of __('Text to translate'), the translations appeared! 

But I tried that on my current project and it didn't work, so I'm trying to figured it out here. I'll keep you posted.

EDIT: It worked on my project as well! I was forgetting to set the context on one string. So everything is good now!

  • Like 2

Share this post


Link to post
Share on other sites

Glad you figured it out! It's interesting why it doesn't work without the context for you. Are you sure you haven't messed up the underscores? There is one in latte files, and two in _strings.php. But I guess you checked that enough times :)

Getting string translation to work is a bit tedious at first, but once you get the hang of it it's easy. Using plurals adds another layer of complexity, even if I tried hard to make it as simple as I can :)

  • Like 1

Share this post


Link to post
Share on other sites

I checked the underscores multiple times, I really don't know what happened. 

I didn't try using plural yet, I'll let you know if I bump on any problem. :) 

Many thanks!

Share this post


Link to post
Share on other sites

You were right, "General" context was used even when it shouldn't. Currently I have no idea how to fix this but will try to come up with something. Since the translator gets only the string to translate, there is nothing to check that it was called "_()" or "_t()", not even calling debug_backtrace.

Share this post


Link to post
Share on other sites

I got it working, but the "General" context will be gone. I think it's even better this way. Will upload a new version soon, after testing the different variations a bit.

  • Like 3

Share this post


Link to post
Share on other sites

v015 is uploaded to GitHub.

Syntax for string translation in .latte files is changed to "{_'text, context, textdomain'}". In textdomain use "__()" if you need no context, and "_x()" if you do.

  • Like 2

Share this post


Link to post
Share on other sites

v015 is uploaded to GitHub.

Syntax for string translation in .latte files is changed to "{_'text, context, textdomain'}". In textdomain use "__()" if you need no context, and "_x()" if you do.

So, in my case, as I'm already using _x(), nothing do do, right? :)

Share this post


Link to post
Share on other sites

Right. Previously the readme contained a wrong syntax for latte files "_('text')", but it shouldn't need the brackets. So if your syntax is also right it would work fine. Clearing latte cache is recommended though. But you should see at once whether it works or not :)

  • Like 2

Share this post


Link to post
Share on other sites

Just upgraded it here, everything seems fine! 

Thank you!

  • Like 1

Share this post


Link to post
Share on other sites

A small contribution to the project readme:

For Sublime Text 3 (should work on 2 too):

  • Install Nette + Latte + Neon package
  • Install Smarty package
  • Set latte extension to open as smarty so you can keep the HTML code autcomplete working

Bonus: install HTML-CSS-JS Prettify package and on its preferences add latte and smarty on allowed file extensions:

"html": {
    "allowed_file_extensions": ["htm", "html", "xhtml", "shtml", "xml", "svg", "latte", "smarty"],

I submitted a pull request editing the readme to add this warning:

HTML Prettify may break lines on strings translations that have more than one word, for instance:
{_'A technical book', 'Books'}

May result in
{_'A 
technical 
book', 'Books'}

so it won't appear translated any more. You'll have to remove the line breaks manually (for now). I'll see if changing something on the package preference does the trick.

Edited by Sérgio

Share this post


Link to post
Share on other sites

Great, thanks! Just updated the readme.

I'm thinking about adding Emogrifier to the module. I have only one usecase for inlining CSS (newsletters) but I think it won't hurt having a "$view->setInlineCSS('path') or similar helper at disposal.

  • Like 1

Share this post


Link to post
Share on other sites

Great, thanks! Just updated the readme.

I'm thinking about adding Emogrifier to the module. I have only one usecase for inlining CSS (newsletters) but I think it won't hurt having a "$view->setInlineCSS('path') or similar helper at disposal.

I think Emogrifier can be handy but should it be part of the module? Why not a different module, so it can work without latte too?

  • Like 1

Share this post


Link to post
Share on other sites

This is my dilemma too. Emogrifier is easy to setup so I'm not sure if it deserves an own module. Of course I'm open to other ideas.

Share this post


Link to post
Share on other sites

Just for the info: latest Nette/Latte plugin for PhpStorm works fine - syntax highlight, autocomplete and such thing works like charm. I will update the module readme later.

  • Like 1

Share this post


Link to post
Share on other sites

v016 was uploaded today to GitHub:

  • enable setting template latte file with/without extension ($view->viewFile = 'basic-page' and $view->viewFile = 'basic-page.latte')
     
  • $view->json_encode returns JSON encoded string/markup. Possible values are true and PHP's json_encode options (eg. JSON_PRETTY_PRINT).
     
  • if "viewFile" begins with "//", $config->paths->templates and viewDir is not prepended to the view path

These updates make it easier to get Ajax results, and allow placing latte files outside templates/views directory. The latter was also possible earlier using relative paths ("../"), but now it's more flexible. Getting json output was only possible using wireRenderFile() and applying json_encode() manually, which was less convenient.

  • Like 5

Share this post


Link to post
Share on other sites

v018 is uploaded with the latest Latte version (2.4.0). There's an official way to set the default layout file so previous workarounds were removed.

  • Like 2

Share this post


Link to post
Share on other sites

Here is an example for an undocumented feature: adding macros.

Put this in 'site/ready.php' (or where you set global parameters for Latte, eg. _init.php or maybe _main.php):

$view->_addMacro['custom iff'] = array(
    'iff',	// macro name
    'if (isset(%node.word) && %node.word) { $x = %node.word;', // PHP code replacing the opening brace
    '}' // // code replacing the closing brace
);

This will add an "iff" macro which eliminates the need of duplicating "$page->title" in the example below:

<h1 n:if="$page->title">{$page->title}</h1>

So instead of writing the above you can use $x:

<h1 n:iff="$page->title">{$x}</h1>

The "iff" macro also uses "isset()" so no worries if you throw in a property that doesn't exists, it won't generate an error.

Using "$x" is arbitrary, you can set any variable name if you wish.

Of course, you can use the alternative syntax too:

{iff $page->title}
<h1>{$x}</h1>
{/iff}

See more in the official docs here on creating macros.

  • Like 2

Share this post


Link to post
Share on other sites

Glad to hear that. Twig felt me a step back after Latte but I haven't really try it in detail.

  • Like 1

Share this post


Link to post
Share on other sites

Hi,

Has anyone succeeded running Hanna Code with Latte template. I'm strugling getting them to work together. Is there  a setting to prevent latte to process Hanna Code tags ?

Thanks.

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