Jump to content

Recommended Posts

Hello,


I still did not solve my problem about Hebrew letters. In fact, it is ok for Russian for example to have a transliteration of characters (one to one) but in languages like Hebrew, Arabic, it is better to slugify with phonetic like here :

use EasySlugger\Utf8Slugger;

$slug = Utf8Slugger::slugify('日本語');  // slug = ri-ben-yu
$slug = Utf8Slugger::slugify('العَرَبِيةُ‎‎');    // slug = alrbyt
$slug = Utf8Slugger::slugify('עברית');  // slug = bryt

So I am planning to insert https://github.com/javiereguiluz/EasySlugger

Should I create a module or just add a hook ?
 

I am a PW newbie.

Thanks for your help

 
  • Like 3

Share this post


Link to post
Share on other sites
On 7/1/2018 at 9:14 PM, Sten said:

Should I create a module or just add a hook ?

I think you should create a module and share it in the modules directory. 🙂
It sounds like it would be very useful for a number of different languages.

If you only want to set the page name once when the page is first created you would hook after Pages::added() and pass the page title to Utf8Slugger::slugify() to get a name. Or if you want the page name to update whenever the title changes you would hook after Pages::saveReady(). For more advanced usages relating to the latter you might like to take a look at the code in @adrian's Page Rename Options module.

  • Like 1

Share this post


Link to post
Share on other sites

Thank you Robin for your help, I will follow your advice and see the Adrian's code to create this module this month.
 

Share this post


Link to post
Share on other sites

Hello,
I began by creating a simple module to slugify the page name.
 

<?php
include $_SERVER['DOCUMENT_ROOT']."/vendor/javiereguiluz/easyslugger/src/SluggerInterface.php";
include $_SERVER['DOCUMENT_ROOT']."/vendor/javiereguiluz/easyslugger/src/Utf8Slugger.php";
use EasySlugger\Utf8Slugger;
class SlugifyExplicit extends WireData implements Module {
public function init() {
    $this->addHookAfter("Pages::added", $this, "slugifyExplicit");
}
public function ___slugifyExplicit($event) {
$pages = $event->object;
$page = $event->arguments(0);
$page->name= Utf8Slugger::slugify($page->title);
$event->return = $page;
}
}

The name is OK but is is not saved in database. Someone has an idea ?

Share this post


Link to post
Share on other sites

@Sten, your module looks like it is missing the required getModuleInfo() method. Check the Module docs for what is required in a module. The Hello World module is a good one to learn from too. And Tracy Debugger is a must-have for debugging modules or anything else (the Tracy bd() method is all you need to learn to begin with).

Also, when you want to make changes to a Page in a Pages::added hook you need to do a $page->save() in order to save the changes.

Not wanting to hijack your module or anything but when you first posted this topic I was interested in EasySlugger and put together a simple module to test it out. I've added a couple of comments to the code that might help you.

<?php namespace ProcessWire;

class Slugger extends WireData implements Module {

    /**
     * Module information
     */
    public static function getModuleInfo() {
        return array(
            'title' => 'Slugger',
            'version' => '0.1.0',
            'autoload' => true,
        );
    }

    /**
     * Ready
     */
    public function ready() {
        // You would generate the slug/name after saveReady or added, but not both
        $this->addHookAfter('Pages::added', $this, 'afterAdded');
        // $this->addHookAfter('Pages::saveReady', $this, 'afterSaveReady');
    }

    /**
     * After Pages::added
     * Set the page name using EasySlugger only once when the page is first added
     *
     * @param HookEvent $event
     */
    protected function afterAdded(HookEvent $event) {
        require_once __DIR__ . '/EasySlugger/SluggerInterface.php';
        require_once __DIR__ . '/EasySlugger/Utf8Slugger.php';
        $page = $event->arguments(0);
        $page->of(false);
        $page->name = \EasySlugger\Utf8Slugger::slugify($page->title);
        $page->save();
    }

    /**
     * After Pages::saveReady
     * Set the page name using EasySlugger every time the page is saved, in case the Title was changed
     * You could add a condition to set the name only if the Title changed if you like
     *
     * @param HookEvent $event
     */
    protected function afterSaveReady(HookEvent $event) {
        require_once __DIR__ . '/EasySlugger/SluggerInterface.php';
        require_once __DIR__ . '/EasySlugger/Utf8Slugger.php';
        $page = $event->arguments(0);
        $page->name = \EasySlugger\Utf8Slugger::slugify($page->title);
    }

}

Slugger.zip

Note that there is a minor core issue with warning notices from ProcessPageAdd that will hopefully be fixed soon: https://github.com/processwire/processwire-issues/issues/648

  • Like 3

Share this post


Link to post
Share on other sites

@Robin S thank you, I tested your module, it works very well with Hebrew. I only put the Javier Reguiluz' app inside the vendor directory to be able to update it with composer. I'll test it more and tell you.

Quote

Note that there is a minor core issue with warning notices from ProcessPageAdd that will hopefully be fixed soon

Yes I saw it too.

I am grateful for your work.

  • Like 1

Share this post


Link to post
Share on other sites

@Robin S @Sten

Actually, this looks really useful. Do you think that you could, between you, publish this module to module directory?

Share this post


Link to post
Share on other sites

@Sten, I was thinking that it would be good to have some configurable options in the module to determine when a page's name is set via EasySlugger. That is what the Page Rename Options module provides, so to avoid recreating all of that I've asked in the support thread if @adrian would consider adding a hookable method to his module.

I think it might be better to bundle EasySlugger in with your module because it will have a wider audience that way - a lot of people are on shared hosting that doesn't include Composer. You could use Composer locally to pull in EasySlugger updates (it actually hasn't received any updates in the last 3 years) and then push them out to your module repo.

Share this post


Link to post
Share on other sites

@Robin S

Quote

if @adrian would consider

Yes good idea.

Quote

I think it might be better to bundle EasySlugger in with your module

OK I understand why it is better haver easySlugger inside the module. Besides I have written to Javier Eguiluz to inform him about our work.

Edited by Sten

Share this post


Link to post
Share on other sites

I don't know much about this, but what about doing it via JS instead of PHP so that it works more seamlessly with PW's approach which is to slugify in realtime with JS. It would also mean automatic integration with the PageRenameOptions module.

Here is some stuff on doing this with JS: https://ourcodeworld.com/articles/read/255/creating-url-slugs-properly-in-javascript-including-transliteration-for-utf-8

On a side note - I guess this doesn't work for your needs, but don't forget that you can change the character replacements by editing the settings for the core InputfieldPageName module.

Share this post


Link to post
Share on other sites
17 hours ago, Sten said:

Yes good idea.

It's actually not as practical an idea as I first thought because PageRenameOptions mostly works via Javascript, as @adrian explained in the support thread. But for the purposes of your module you probably don't need all the config options that PageRenameOptions provides. The "initial differences protected" option would be the main one and I think it will be possible to achieve that in PHP with the API. I'll give it a try and post something later.

 

42 minutes ago, adrian said:

I don't know much about this, but what about doing it via JS instead of PHP so that it works more seamlessly with PW's approach which is to slugify in realtime with JS.

I see this the other way around - I think it would actually be better if PW moved to a PHP/API implementation for setting the page name. It's a bit of a problem IMO that there is no API method that provides identical naming to the JS naming in ProcessPageAdd. And I don't think the approach of requiring users of languages other than English to enter potentially thousands of character transliterations into the InputfieldPageName config is ideal.

Although I don't work on non-English sites myself I think it would be good to have something like EasySlugger in the PW core, with the InputfieldPageName config only used for custom overrides. So the user only enters a title in the first step of Page Add and the page name is derived from the title in PHP. The user can easily change to a custom page name after that if need be, so it's not much of a sacrifice in return for a more consistent naming system that requires less configuration.

 

  • Thanks 1

Share this post


Link to post
Share on other sites

@Robin S. Great I'll look at it soon. Thank you Robin, I would not have done anything without your help.

  • Like 1

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 MoritzLost
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory (pending approval) Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
    • By joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="text/plain" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: PrivacyWire Git Repo
      Download as .zip
      I would love to hear your feedback 🙂
      CHANGELOG
      0.1.1 Debugging: fixed error during uninstall 0.1.0 Added new detection of async scripts for W3C Validation 0.0.6 CSS-Debugging for hiding unused buttons, added ProCache support for the JavaScript tag 0.0.5 Multi-language support included completely (also in TextFormatter). Added possibility to async load other assets (e.g. <img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">) 0.0.4 Added possibility to add an imprint link to the banner 0.0.3 Multi-language support for module config (still in development) 0.0.2 First release 0.0.1 Early development
    • By bernhard
      --- Please use RockFinder3 ---
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory (pending approval) If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By Craig
      I've been using Fathom Analytics for a while now and on a growing number of sites, so thought it was about time there was a PW module for it.
      WayFathomAnalytics
      WayFathomAnalytics is a group of modules which will allow you to view your Fathom Analytics dashboard in the PW admin panel and (optionally) automatically add and configure the tracking code on front-end pages.
      Links
      GitHub Readme & documentation Download Zip Modules directory Module settings screenshot What is Fathom Analytics?
      Fathom Analytics is a simple, privacy-focused website analytics tool for bloggers and businesses.

      Stop scrolling through pages of reports and collecting gobs of personal data about your visitors, both of which you probably don't need. Fathom is a simple and private website analytics platform that lets you focus on what's important: your business.
      Privacy focused Fast-loading dashboards, all data is on a single screen Easy to get what you need, no training required Unlimited email reports Private or public dashboard sharing Cookie notices not required (it doesn't use cookies or collect personal data) Displays: top content, top referrers, top goals and more
×
×
  • Create New...