Jump to content

MoritzLost

Members
  • Posts

    366
  • Joined

  • Last visited

  • Days Won

    18

Everything posted by MoritzLost

  1. This doesn't warrant a full tutorial, but I wrote a little function that will recursively search through a repeater field to find the first non-empty field matching a list of fields to look for. I needed something like this to generate a fallback for SEO fields (og:image, og:description et c.). Here it is: <?php namespace ProcessWire; /** * Find the first non-empty field out of a list of fields in a repeater or repeater matrix field. * Will recursively search through nested repeaters until it finds a non-empty * field. * * @param RepeaterPageArray $repeater The field to search through. * @param array $fields A list of fields the function should look for. * @param array|null $allowed_repeater_types All the Repeater Matrix types the function will check. Leave empty to allow all. * @param array|null $allowed_repeater_fields All the repeater fields the function will check recursively. Leave empty to allow all. * @return void */ function firstRecursiveRepeaterMatch( RepeaterPageArray $repeater, array $fields, ?array $allowed_repeater_types = null, ?array $allowed_repeater_fields = null ) { // iterate over the items of the repeater foreach ($repeater as $current) { // if the function is currently inside a repeater matrix field, // skip this item if it isn't one of the allowed types, unless // allowed_repeater_types is empty (all types allowed) if ( $current instanceof RepeaterMatrixPage && is_array($allowed_repeater_types) && !in_array($current->type, $allowed_repeater_types) ) { continue; } // get all fields of the current item foreach ($current->getFields() as $field) { $name = $field->name; // if the current field is another repeater, check it recursively $fieldtype_class = $field->getFieldType()->className(); if ($fieldtype_class === 'FieldtypeRepeater' || $fieldtype_class === 'FieldtypeRepeaterMatrix') { // continue with the next item if the field name isn't one of the // allowed repeater fields, unless allowed_repeater_fields empty (null) if ( is_array($allowed_repeater_fields) && !in_array($name, $allowed_repeater_fields) ) { continue; } $deep_search = firstRecursiveRepeaterMatch( $current->get($name), $fields, $allowed_repeater_types, $allowed_repeater_fields ); // if the deep search inside the repeater // finds something, the function ends here if ($deep_search !== null) { return $deep_search; } } // if the current field name is one of the requested // fields, return it's value if it isn't empty if (in_array($name, $fields)) { $value = $current->get($name); if ( // check for empty values !empty($value) // if the value is any wirearray, check // if it has at least one item && (!$value instanceof WireArray || $value->count() > 0) ) { return $value; } } } } // if the function reaches this point, there is no match in the entire tree return null; } Can be used like this: $seo_description = firstRecursiveRepeaterMatch( // content sections fields, a repeater matrix with multiple types $page->sections, // look for the first non-empty instance of any of those fields ['body', 'html_basic', 'html_full'], // only check sections of the following types ['section_text', 'section_columns', 'section_accordion'], // only check the following nested repeaters recursively ['columns', 'accordion'] ); Wanted to share because I thought it could be useful to others. It should be easy to adjust the matching condition from non-emtpy fields to some other condition, depending on the use case ...
  2. @szabesz Fair enough! ? @adrian As a user, I agree - i don't like it when I try to navigate away from a page using a link, and it opens in a new page, forcing me to go back to close the tab. But we're power users, I'm not sure everyone knows how to open links in a new tab (especially on mobile, not everyone gets the long-press interaction!). As for why I still use target blank basically for all external links, you know, business reasons. Almost every client sees red when they encounter a link that leads them away from their site. Not sure why everyone expects their audience to have the attention span of a mouse, but oh well ... it's not something I want to spend energy discussing every time. I can see both sides though.
  3. @adrian @horst @szabesz Thanks! Interesting how those solutions are different yet similar. I usually do something like this for footer menus that tend to be more custom, since it only contains a cherry-picked selection of the most important pages. I have tried a couple different combinations of fields, with different levels of control. Since we're doing screenshots, here's the latest iteration that I find quite flexible: Sorry it's in German. Basically, there's a repeater "Footer regions", each containing a headline and a repeater with links. The regions get displayed as individual columns in the footer. Each link has a radio selection between "Internal page", "External URL" and "Download", and a "Link-Text" field. Depending on the radio selection, the respective field get displayed (page reference, URL or file Upload). If the Link-Text is empty, the link is displayed with a reasonable default (Page title for internal pages, domain for external URLs, file basename for files). I initially disliked having too use an additional field for the link-type, but it provides better usability for the client in my experience. @horst I like the solution with the show_only_if fields, though it might not be clear to clients how to switch it back? I found that the interaction with fields being only visible when other fields are empty/filled is not so intuitive for clients. @szabesz Interesting, is the "Open blank" option something your clients actively use? I usually just handle that in the template, i.e. all URLs to different hosts get target="_blank" rel="noopener" automatically ...
  4. In this tutorial I want to write about handling special cases and change requests by clients gracefully without introducing code bloat or degrading code quality and maintainability. I'll use a site's navigation menu as an example, as it's relatable and pretty much every site has one. I'll give some examples of real situations and change requests I encountered during projects, and describe multiple approaches to handling them. However, this post is also about the general mindset I find useful for ProcessWire development, which is more about how to handle special cases and still keep your code clean by making the special case a normal one. The problem: Special cases everywhere Since ProcessWire has a hierarchical page tree by default, as a developer you'll usually write a function or loop that iterates over all children of the homepage and displays a list of titles with links. If the site is a bit more complex, maybe you additionally loop over all grandchildren and display those in drop-down menus as well, or you even use a recursive function to iterate over an arbitrary amount of nested child pages. Something like this: function buildRecursiveMenu(Page $root): string { $markup = ['<ul class="navigation">']; foreach ($root->children() as $child) { $link = '<a class="navigation__link" href="' . $child->url() . '">' . $child->title . '</a>'; $children = $child->hasChildren() ? buildRecursiveMenu($child) : ''; $markup[] = "<li class="navigation__item">{$link}{$children}</li>"; } $markup[] = '</ul>'; return implode(PHP_EOL, $markup); } But then the requests for special cases come rolling in. For example, those are some of the requests I've gotten from clients on my projects (by the way, I'm not saying the clients were wrong or unreasonable in any of those cases - it's simply something I needed to handle in a sensible way): The homepage has the company's name as it's title, but the menu link in the navigation should just say "Home". The first page in a drop-down menu should be the top-level page containing the drop-down menu. This was requested because the first click on the top-level item opens the sub-navigation instead of navigating to that page (espcially on touch devices, such as iPads, where you don't have a hover state!), so some visitors might not realize it's a page itself. Some top-level pages should be displayed in a drop-down menu of another top-level page, but the position in the page tree can't change because of the template family settings. The menu needs to contain some special links to external URLs. For one especially long drop-down menu, the items should be sorted into categories with subheadings based on a taxonomy field. In general, my solutions to those requests fall into three categories, which I'll try to elaborate on, including their respective benefits and downsides: Checking for the special case / condition in the code and changing the output accordingly (usually with hard-coded values). Separating the navigation menu from the page tree completely and building a custom solution. Utilizing the Content Management Framework by adding fields, templates and pages that represent special states or settings. Handling it in the code This is the simplest solution, and often the first thing that comes to mind. For example, the first request (listing the homepage as "Home" instead of it's title in the navigation) can be solved by simply checking the template or ID of the current page inside the menu builder function, and changing the output accordingly: // ... $title = $child->template->name === 'home' ? 'Home' : $child->title; $link = '<a class="navigation__link" href="' . $child->url() . '">' . $title . '</a>'; // ... This is definitely the fastest solution. However, there are multiple downsides. Most notably, it's harder to maintain, as each of those special cases increases the complexity of the menu builder function, and makes it harder to change. As you add more special conditions, it becomes exponentially harder to keep changing it. This is the breeding ground for bugs. And it's much harder to read, so it takes longer for another developer to pick up where you left (or, as is often cited, for yourself in six months). Also, now we have a hard-coded value inside the template, that only someone with access to and knowledge of the template files can change. If the client want's the link to say "Homepage" instead of "Home" at some point, they won't be able to change it without the developer. Also, each special case that is hidden in the code makes it harder for the client to understand what's going on in terms of template logic - thus increasing your workload in editorial support. That said, there are definitely some times where I would go with this approach. Specifically: For smaller projects that you know won't need to scale or be maintained long-term. If you are the only developer, and/or only developers will edit the site, with no "non-technical" folk involved. For rapid prototyping ("We'll change it later") Building a custom solution My initial assumption was that the main navigation is generated based on the page tree inside ProcessWire. But of course this isn't set in stone. You can just as easily forgo using the page tree hierarchy at all, and instead build a custom menu system. For example, you could add a nested repeater where you can add pages or links on a general settings page, and generate the menu based on that. There are also modules for this approach, such as the Menu Builder by @kongondo. This approach is not the quickest, but gives the most power to the editors of your site. They have full control over which pages to show and where. However, with great power comes great responsibility, as now each change to the menu must be performed manually. For example, when a new page is added, it won't be visible in the menu automatically. This is very likely to create a disconnect between the page tree and the menu (which may be what you want, after all). You may get ghost pages that are not accessible from the homepage at all, or the client may forgot to unpublish pages they don't want to have any more after they've removed them from the menu. I would only go with this approach if there are so many special cases that there hardly is a "normal case". However, even then it might not be the best solution. The direct relationship between the page tree, the menu structure and page paths are one of the strongest features of ProcessWire in my opinion. If many pages need to be placed in special locations without much structure in regards to what templates go where, maybe you only need to loosen up the template family settings. I have built one site without any template family restrictions at all - any page of any template can go anywhere. It's definitely a different mindset, but in this case it worked well, because it allowed the client to build custom sections with different page types grouped together. It's a trade-off, as it is so often, between flexibility and workload. Weigh those options carefully before you choose this solution! Utilizing the CMF This is the middle ground between the two options above. Instead of building a completely custom solution, you keep with the basic idea of generating a hierarchical menu based on the page tree, but add fields and templates that allow the editor to adjust how and where individual pages are displayed, or to add custom content to the menu. of course, you will still write some additional code, but instead of having hard-coded values or conditions in the template, you expose those to the client, thereby making the special case one of the normal cases. The resulting code is often more resilient to changing requirements, as it can not one handle that specific case that the client requested, but also every future change request of the same type. The key is to add fields that enable the client to overwrite the default behaviour, while still having sensible defaults that don't require special attention from the editor in most cases. I'll give some more examples for this one, as I think it's usually the best option. Example 1: Menu display options This is probably the first thing you thought of for the very first change request I mentioned (displaying the homepage with a different title). Instead of hard-coding the title "Home" in the template, you add a field menu_title that will overwrite the normal title, if set. This is definitely cleaner than the hard-coded value, since it allows the client to overwrite the title of any page in the menu. I'll only say this much in terms of downsides: Maybe the menu title isn't really what the client wanted - instead, perhaps they feel limited because the title is also displayed as the headline (h1) of the page. In this case, the sensible solution would be an additional headline field that will overwrite the h1, instead of the menu_title field. Which fields are really needed is an important consideration, because you don't want to end up with too many. If each page has fields for the title, a headline, a menu title and an SEO-title, it's much more complicated than it needs to be, and you will have a hard time explaining to the client what each field is used for. Another example in this category would be an option to "Hide this page in the menu". This could be accomplished by hiding the page using the inbuilt "hidden" status as well, but if it's hidden it won't show up in other listings as well, so separating the menu display from the hidden status might be a good idea if your site has lots of page listings. Example 2: "Menu link" template One solution that is quite flexible in allowing for custom links to pages or external URLs is creating a menu-link template that can be placed anywhere in the page tree. This templates can have fields for the menu title, target page and/or external target URL. This way, you can link to another top-level page or an external service inside a drop-down menu, by placing a Menu Link page at the appropriate position. This is also a clean solution, because the navigation menu will still reflect the page tree, making the custom links visible and easily editable by the editors. A minor downside is that those templates are non-semantical in the sense that they aren't pages with content of their own. You'll need to make sure not to display them in listings or in other places, as they aren't viewable. It may also require loosening up strict family rules - for example, allowing for Menu Link pages to be placed below the news index page, which normally can only hold news pages. Example 3: Drop-down menu override This one is a more radical solution to override drop-down menus. You add a repeater field to top-level pages, similar to the one mentioned as a custom solution, where you can add multiple links to internal pages or URLs. If the repeater is empty, the drop-down menu is generated normally, based on the sub-pages in the page tree. But if the repeater contains some links, it completely overrides the drop-down menu. It's similar to the fully custom solution in that as soon as you override a sub-menu for a top-level page, you have to manually manage it in case the page structure changes. But you can make that decision for each top-level page individually, so you can leave some of them as is and only have to worry about the ones that you have overwritten. Again, this offers sensible defaults with good customizability. A downside is that the mixed approach may confuse the client, if some changes to the page tree are reflected in the drop-down menu directly, while others don't seem to have any effect (especially if you have multiple editors working on a site). Finding the right solution So how do you choose between the approaches? It depends on the client, the requirements, and on what special cases you expect and want to handle. Sometimes, a special request can be turned down by explaining how it would complicate editorial workflows or have a negative impact on SEO (for example, if you risk having some pages not accessible from the homepage at all). Also, make sure you understand the actual reason behind a change request, instead of just blindly implementing the suggestion by the client. Often, clients will suggest solutions without telling you what the actual problem is they're trying to solve. For example: In one case, I implemented the drop-down override mentioned in example three. However, what the client really wanted was to have the top-level page as the first item in the drop-down menu (see the example requests mentioned above). So they ended up overwriting every single drop-down menu, making the menu harder to maintain. In this case, it would have been better to go with a more specialized solution, such as adding a checkbox option, or even handling it in the code, since it would have been consistent throughout the menu. Another example was mentioned above: If the client requests an additional "Menu title" field, maybe what they really need is a "Headline" field. I recommend reading Articulating Design Decisions by Tom Greever; it includes some chapters on listening to the client, finding out the real reason behind a change request, and responding appropriately. It's written from a design perspective, but is applicable to development as well, and since UX becomes more important by the day, the lines between the disciplines are blurred anyway. Conclusion I realize now this reads more like a podcast (or worse, a rant) than an actual tutorial, but hopefully I got my point across. ProcessWire is at is greatest if you utilize it as a Content Management Framework, creating options and interfaces that allow for customizability while retaining usability for the client / editor. I usually try to hit a sweet spot where the editors have maximum control over the relevant aspects of their site, while requiring minimal work on their part by providing sensible defaults. Above, I listed some examples of requests I've gotten and different solutions I came up with to handle those with custom fields or templates. Though in some cases the requirements call for a custom solution or a quick hack in the template code as well! What are some of the special requests you got? How did you solve them? I'd love to get some insights and examples from you. Thanks for reading!
  5. @valan You need to include both the autoloader from Composer and the ProcessWire bootstrap file, see Bootstrapping ProcessWire CMS. Assuming your autoloader lives under prj/vendor/autoload.php and the webroot with the ProcessWire installation under prj/web/, you can use the following at the top of your script: # prj/console/myscript.php <?php namespace ProcessWire; # include composer autoloader require __DIR__ . '/../vendor/autoload.php'; # bootstrap processwire require __DIR__ . '/../web/index.php'; ProcessWire will detect that it is being included in this way and automatically load all the API variables (and the functions API, if you are using that). Keep in mind that there will be no $page variable, as there is no HTTP request, so there is no current page.
  6. @iipa You need to use the correct namespace by either aliasing the class with the use statement, or by using a fully qualified class name. As others have said though, it's much easier to use Composer with it's autoloader, since you only need to include it once and all classes will be autoloaded. It's also better for performance, as only the classes you actually use get loaded for each request. If you need help setting up Composer and the autoloader, check out my tutorial on Composer + ProcessWire ?
  7. @stanoliver Assuming the text from your datarow field looks something like this: 100,200,300,400,500 You can use the explode function to split the string into an array using the commas as a delimiter. For example: $prices = explode(',', $page->datarow); // ["100", "200", "300", "400", "500"]
  8. @Pixrael Thanks, that makes perfect sense. Are you sure the query parameter doesn't work? It really should, since it's a different request and may return different results for some services. Maybe Chrome is employing some heuristics to determine that it's always the same image ... though it isn't in your case ... I don't know, sounds curious. In any case, your HTTP-header method is probably the best approach for this scenario! Though you really only need the Cache-Control header; Expires, ETag and and Pragma are superfluous except for the most legacy of legacy browsers ? @dragan Firefox Developer Edition master race! ? Though I don't always have the Developer Tools open while writing my templates, and as you said I frequently need to test on other devices, so I prefer the caching busting approach. I usually have a $config->theme_version parameter in my config that gets appended to each CSS / JS URL, this way I can also easily invalidate caches on live sites when I push an update. During development (coupled to $config->debug) I just append the current timestamp, so the parameter changes for each request.
  9. @Pixrael A simpler approach that doesn't require any server-side adjustments at all would be to include the cache-busting parameter as a query variable instead. For example: /site/downloads/9VefFf6vstUR0q1ywzPgjXw4PfAgYqGp.png?v=1562618833 I use something like this during development for my CSS / JS assets, so the browser downloads those anew for each request and I see all changes immediately ... The browser will not use the cached image if the query string differs. This way you don't need to rewrite any URLs in Apache. I would also strongly advise not to go with the second approach (using HTTP-headers to disable caching), as this way the images can never be cached and reused, which means your site takes a major performance hit. Can I ask why you need to do this at all? If the browser has already loaded the image, why force it to load it again?
  10. @stanoliver I don't quite understand your situation, but if you have some data in an array, you have a couple of methods to output it. A simple foreach loop will keep the code at the same length regardless of how many columns you need: $prices = [ '100', '200', '300', '400', '500' ]; foreach ($prices as $price) { echo $price . ' '; } // output: // 100 200 300 400 500 // note there's one final space after "500" If you need to have something in between each item, for example a comma for CSV-style notation, you can use implode: $prices = [ '100', '200', '300', '400', '500' ]; echo implode(', ', $prices); // output: // 100, 200, 300, 400, 500 Finally, if you need to add something before or after each item or manipulate the items in some way, you can use array_map, which applies a callback function to each element of the array and returns a new array with the return values. For example, to wrap each element in double quotes for the CSV delimiters: $prices = [ '100', '200', '300', '400', '500' ]; echo implode(',', array_map(function ($price) { return '"' . $price . '"'; }, $prices)); // output: // "100","200","300","400","500"
  11. @stanoliver Great ? Array elements that are declared without a key are implicitly numeric in PHP, so the following declarations are equivalent: $colors = [ 'red', 'green', 'blue', ]; $colors = [ 0 => 'red', 1 => 'green', 2 => 'blue', ]; You can even mix numerical and associative arrays, but that only leads to confusion in my opinion, so I would avoid it.
  12. Just to clarify, which part don't you understand? The $data object is an associative array, so you can access the colors using the respective key: $colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue'] The $colors array is an indexed / numerical array (i.e. it's not associativ), so you can access each of the colors using the numerical key of the position you want: $colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue'] echo $colors[0]; // red echo $colors[2]; // blue Or are you stuck on how to use the meta method itself?
  13. Just to expand on this, having seperate methods for getting and setting are preferable because you can use typehints to declare argument and return types. This way, your methods become more robust (invalid arguments produce errors instead of propagating through your application and causing errors elsewhere), and your IDE / code editor can use them to provide better hints while using the methods. If you have just one method for both, you can't use a return typehints, because the function might return a string or an object. To expand on your two methods: public function setText(string $value): self { $this->text = trim($value); return $this; } public function getText(): string { return $this->text; } I'm looking forward to PHP 7.4 which will have typed class properties. Then we'll be able to get rid of the getText method altogether: public string $text; public function setText(string $value): self { $this->text = trim($value); return $this; }
  14. @Tyssen @teppo Yeah that was a mistake, sorry about that. I always add the twig instances to the config to be able to access them globally, but here I didn't include that part. I corrected it in the OP! Yeah, I think setting the output as a variable in the _init.php or _main.php is the best option here, since you can't directly call static methods of classes in twig. Another option, if it's a method you need to access more often, is to write a wrapper twig function and add it to your twig environment. There are some example for this in the second part of the tutorial - let me know if it's not working for you!
  15. No special reason, to be honest. I just don't use the sanitizer that much, so it's easier for me to write some regex than using the sanitizer. Though I did want some special replacements (for German umlauts ä, ü and ö for example) that I'm not sure the sanitizer can handle.
  16. This is part two of my tutorial on integrating Twig in ProcessWire sites. As a reminder, here's the table of contents: Part 1: Extendible template structures How to initialize a custom twig environment and integrate it into ProcessWire How to build an extendible base template for pages, and overwrite it for different ProcessWire templates with custom layouts and logic How to build custom section templates based on layout regions and Repeater Matrix content sections Part 2: Custom functionality and integrations How to customize and add functionality to the twig environment How to bundle your custom functionality into a reusable library Thoughts on handling translations A drop-in template & functions for responsive images as a bonus Make sure to check out part one if you haven't already! This part will be less talk, more examples, so I hope you like reading some code ? Adding functionality This is more generic Twig stuff, so I'll keep it short, just to show why Twig is awesome and you should use it! Twig makes it super easy too add functions, filters, tags et c. and customize what the language can do in this way. I'll show a couple of quick examples I built for my projects. As a side note, I had some trouble with functions defined inside a namespace that I couldn't figure out yet. For the moment, it sufficed to define the functions I wanted to use in twig inside a separate file in the root namespace (or, as shown further below, put all of it in a Twig Extension). If you want a more extensible, systematic approach, check out the next section (going further). Link template with external target detection This is a simple template that builds an anchor-tag (<a>) and adds the necessary parameters. What's special about this is that it will automatically check the target URL and include a target="_blank" attribute if it's external. The external URL check is contained in a function: // _functions.php /** * Finds out whether a url leads to an external domain. * * @param string $url * @return bool */ function urlIsExternal(string $url): bool { $parser = new \League\Uri\Parser(); [ 'host' => $host ] = $parser->parse($url); return $host !== null && $host !== $_SERVER['HTTP_HOST']; } // _init.php require_once($config->paths->templates . '_functions.php'); // don't forget to add the function to the twig environment $twig_env->addFunction(new \Twig\TwigFunction('url_is_external', 'urlIsExternal')); This function uses the excellent League URI parser, by the way. Now that the function is available to the Twig environment, the link template is straightforward: {# # Renders a single anchor (link) tag. Link will automatically # have target="_blank" if the link leads to an external domain. # # @var string url The target (href). # @var string text The link text. Will default to display the URL. # @var array classes Optional classes for the anchor. #} {%- set link_text = text is not empty ? text : url -%} <a href="{{ url }}" {%- if classes is not empty %} class="{{ classes|join(' ') }}"{% endif %} {%- if url_is_external(url) %} target="_blank"{% endif %}> {{- link_text -}} </a> String manipulation A couple of functions I wrote to generate clean meta tags for SEO, as well as valid, readable IDs based on the headline field for my sections. /** * Truncate a string if it is longer than the specified limit. Will append the * $ellipsis string if the input is longer than the limit. Pass true as $strip_tags * to strip all markup before measuring the length. * * @param string $text The text to truncate. * @param integer $limit The maximum length. * @param string|null $ellipsis A string to append if the text is truncated. Pass an empty string to disable. * @param boolean $strip_tags Strip markup from the text? * @return string */ function str_truncate( string $text, int $limit, ?string $ellipsis = ' …', bool $strip_tags = false ): string { if ($strip_tags) { $text = strip_tags($text); } if (strlen($text) > $limit) { $ell_length = $ellipsis ? strlen($ellipsis) : 0; $append = $ellipsis ?? ''; $text = substr($text, 0, $limit - ($ell_length + 1)) . $append; } return $text; } /** * Convert all consecutive newlines into a single space character. * * @param string $text The text to convert. */ function str_nl2singlespace( string $text ): string { return preg_replace( '/[\r\n]+/', ' ', $text ); } /** * Build a valid html ID based on the passed text. * * @param string $title * @return string */ function textToId(string $title): string { return strtolower(preg_replace( [ '/[Ää]/u', '/[Öö]/u', '/[Üü]/u', '/ß/u', '/[\s._-]+/', '/[^\w\d-]/', ], [ 'ae', 'oe', 'ue', 'ss', '-', '-', ], $title )); } // again, add those functions to the twig environment $twig_env->addFilter(new \Twig\TwigFilter('truncate', 'str_truncate')); $twig_env->addFilter(new \Twig\TwigFilter('nl2ss', 'str_nl2singlespace')); $twig_env->addFilter(new \Twig\TwigFilter('text_to_id', 'textToId')); Example usage for SEO meta tags: {% if seo.description %} {% set description = seo.description|truncate(150, ' …', true)|nl2ss %} <meta name="description" content="{{ description }}"> <meta property="og:description" content="{{ description }}"> {% endif %} instanceof for Twig By default, Twig doesn't have an equivalent of PHP's instanceof keyword. The function is super simple, but vital to me: // instanceof test for twig // class must be passed as a FQCN with escaped backslashed $twig_env->addTest(new \Twig\TwigTest('instanceof', function ($var, $class) { return $var instanceof $class; })); In this case, I'm adding a TwigTest instead of a function. Read up on the different type of extensions you can add in the documentation for Extending Twig. Note that you have to use double backslashes to use this in a Twig template: {% if og_img is instanceof('\\Processwire\\Pageimages') %} Going further: custom functionality as a portable Twig extension Most of the examples above are very general, so you'll want to have them available in every project you start. It makes sense then to put them into a single library that you can simply pull into your projects with git or Composer. It's really easy to wrap functions like those demonstrated above in a custom Twig extension. In the following example, I have wired the namespace "moritzlost\" to the "src" folder (see my Composer + ProcessWire tutorial if you need help with that): // src/MoritzFuncsTwigExtension.php <?php namespace moritzlost; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; use Twig\TwigFilter; use Twig\TwigTest; class MoritzFuncsTwigExtension extends AbstractExtension { // import responsive image functions use LinkHelpers; public function getFunctions() { return [ new TwigFunction('url_is_external', [$this, 'urlIsExternal']), ]; } public function getFilters() { return [ new TwigFilter('text_to_id', [$this, 'textToId']), ]; } public function getTests() { return [ new TwigTest('instanceof', function ($variable, string $namespace) { return $variable instanceof $namespace; }), ]; } } // src/LinkHelpers.php <?php namespace moritzlost; trait LinkHelpers { // this trait contains the textToId and urlIsExternal methods // see the section above for the full code } Here I'm building my own class that extends the AbstractExtension class from Twig. This way, I can keep boilerplate code to a minimum. All I need are public methods that return an array of all functions, filters, tests et c. that I want to add with this extension. As is my custom, I've further split the larger functions into their own wrapper file. In this case, I'm using a trait to group the link-related functions (it's easier this way, since classes can only extend one other class, but use as many traits as they want to). Now all that's left is to add an instance of the extension to our Twig environment: // custom extension to add functionality $twig_env->addExtension(new MoritzFuncsTwigExtension()); Just like that we have a separate folder that can be easily put under version control and released as a micro-package that can then be installed and extended in other projects. Translations If you are building a multi-language site, you will need to handle internationalization of your code. ProcessWire can't natively handle translations in Twig files, so I wanted to briefly touch on how to handle this. For a recent project I considered three approaches: Build a module to add twig support to ProcessWire's multi-language system. Use an existing module to do that. Build a custom solution that bypasses ProcessWire's translation system. For this project, I went with the latter approach; I only needed a handful of phrases to be translated, as I tend to make labels and headlines into editable page fields or use the field labels themselves, so there are only few translatable phrases inside my ProcessWire templates. But the beauty of ProcessWire is that you can build your site whatever way you want. As an example, here's the system I came up with. I used a single Table field (part of the ProFields module) with two columns: msgid (a regular text field which functions as a key for the translations) and trans (a multi-language text field that holds the translations in each language). I added this field to my central settings page and wrote a simple function to access individual translations by their msgid: /** * Main function for the translation API. Gets a translation for the msgid in * the current language. If the msgid doesn't exist, it will create the * corresponding entry in the settings field (site settings -> translations). * In this case, the optional second parameter will be used as the default * translation for this msgid in the default language. * * @param string $msgid * @param ?string $default * @return string */ function trans_api( string $msgid, ?string $default = null ): string { // this is a reference to my settings page with the translations field $settings = \Processwire\wire('config')->settings; $translations = $settings->translations; $row = $settings->translations->findOne("msgid={$msgid}"); if ($row) { if ($row->trans) { return $row->trans; } else { return $msgid; } } else { $of = $settings->of(); $settings->of(false); $new = $translations->makeBlankItem(); $new->msgid = $msgid; if ($default) { $default_lang = \Processwire\wire('languages')->get('default'); $new->trans->setLanguageValue($default_lang, $default); } $settings->translations->add($new); $settings->save('translations'); $settings->of($of); return $default ?? $msgid; } } // _init.php // add the function with the key "trans" to the twig environment $twig_env->addFunction(new \Twig\TwigFunction('trans', 'trans_api')); // some_template.twig // example usage with a msgid and a default translation {{ trans('detail_link_label', 'Read More') }} This function checks if a translation with the passed msgid exists in the table and if so, returns the translation in the current language. If not, it automatically creates the corresponding row. This way, if you want to add a translatable phrase inside a template, you simply add the function call with a new msgid, reload the page once, and the new entry will be available in the backend. For this purpose, you can also add a second parameter, which will be automatically set as the translation in the default language. Sweet. While this works, it will certainly break (in terms of performance and user-friendliness) if you have a site that required more than a couple dozen translations. So consider all three approaches and decide what will work best for you! Bonus: responsive image template & functions I converted my responsive image function to a Twig template, I'm including the full code here as a bonus and thanks for making it all the way through! I created a gist with the extension & and template that you can drop into your projects to create responsive images quickly (minor warning: I had to adjust the code a bit to make it universal, so this exact version isn't properly tested, let me know if you get any errors and I'll try to fix it!). Here's the gist. There's a usage example as well. If you don't understand what's going on there, make sure to read my tutorial on responsive images with ProcessWire. Conclusion Including the first part, this has been the longest tutorial I have written so far. Again, most of this is opinionated and influenced by my own limited experience (especially the part about translations), so I'd like to hear how you all are using Twig in your projects, how you would improve the examples above and what other tips and tricks you have!
  17. This won't work, you need to use the require command to add dependencies to your project. This will add the dependency to your composer.json and download it. The install command is used to read the composer.lock file and download all the dependencies listed in there, as well as update the autoloader. This is why install doesn't take a library as an argument. @bramwolf Pretty sure that BitPoet is right. That error indicates that the class ProcessWire\PaymentModule doesn't exist. If you installed the PaymentModule through the backend or downloaded it from the module page, you would get the master branch, which doesn't have the correct namespace. So this version of the module would have the \PaymentModule class inside the root namespace, but not inside the Processwire namespace (which is what the PaymentMollie module tries to extend). Install the PW3 branch and you should be fine.
  18. Thanks! Though this does require running Composer in the project / web root, which I don't like, see the post above. I had considered TemplateEngineTwig for a recent project when I wanted to work with Twig instead of pure PHP templates, but I ended up writing my custom integration, which makes use of the setup I described here. See my newest tutorial on that ^^
  19. Sounds like your issue is in fact with the ProcessWire module. But if you need help integrating the Mollie SDK, I wrote a tutorial on setting up Composer with ProcessWire, this includes how to initialize a Composer project, require (i.e. install) third-party dependendencies and connect the autoloader. If you're having problems with the setup, let me know in the comments and I'll try to answer ? A good place to install the libraries is one directory above the webroot. since you don't want individual files of external libraries to be publicly accessible (since this opens up quite a lot of security issues). My tutorial includes an explanation of the directory structure I would recommend.
  20. I have recently started to integrate Twig in my ProcessWire projects to have a better separation between logic and views as well as have cleaner, smaller template files as opposed to large multi-purpose PHP-templates. Though there is a Twig module, I have opted to initialize twig manually to have more control over the structure and settings of the twig environment. This is certainly not required to get started, but I find that having no "secret sauce" gives the me as a developer more agency over my code structure, and better insights into how the internals of the libraries I'm using work. Framework like Drupal or Craft have their own Twig integration, which comes with some opinionated standards on how to organize your templates. Since Twig is not native to ProcessWire, integrating Twig requires one to build a solid template structure to be able to keep adding pages and partials without repeating oneself or having templates grow to unwieldy proportions. This will be an (opinionated) guide on how to organize your own flexible, extensible template system with ProcessWire and Twig, based on the system I developed for some projects at work. Somehow this post got way too long, so I'm splitting it in two parts. I will cover the following topics: Part 1: Extendible template structures How to initialize a custom twig environment and integrate it into ProcessWire How to build an extendible base template for pages, and overwrite it for different ProcessWire templates with custom layouts and logic How to build custom section templates based on layout regions and Repeater Matrix content sections Part 2: Custom functionality and integrations How to customize and add functionality to the twig environment How to bundle your custom functionality into a reusable library Thoughts on handling translations A drop-in template & functions for responsive images as a bonus However, I will not include a general introduction to the Twig language. If you are unfamiliar with Twig, read the Twig guide for Template Designers and Twig for Developers and then come back to this tutorial. That's a lot of stuff, so let's get started ? Initializing the Twig environment First, we need to install Twig. If you set up your site as described in my tutorial on setting up Composer, you can simply install it as a dependency: composer require "twig/twig:^2.0" I'll initialize the twig environment inside a prependTemplateFile and call the main render function inside the appendTemplateFile. You can use this in your config.php: $config->prependTemplateFile = '_init.php'; $config->appendTemplateFile = '_main.php'; Twig needs two things: A FilesystemLoader to load the templates and an Environment to render them. The FilesystemLoader needs the path to the twig template folder. I'll put my templates inside site/twig: $twig_main_dir = $config->paths->site . 'twig'; $twig_loader = new \Twig\Loader\FilesystemLoader($twig_main_dir); As for the environment, there are a few options to consider: $twig_env = new \Twig\Environment( $twig_loader, [ 'cache' => $config->paths->cache . 'twig', 'debug' => $config->debug, 'auto_reload' => $config->debug, 'strict_variables' => false, 'autoescape' => true, ] ); if ($config->debug) { $twig_env->addExtension(new \Twig\Extension\DebugExtension()); } Make sure to include a cache directory, or twig can't cache the compiled templates. The development settings (debug, auto_reload) will be dependent on the ProcessWire debug mode. I turned strict_variables off, since it's easier to check for non-existing and non-empty fields with some parts of the ProcessWire API. You need to decide on an escaping strategy. You can either use the autoescape function of twig, or use textformatters to filter out HTML tags (you can't use both, as it will double escape entities, which will result in a broken frontend). I'm using twig's inbuilt autoescaping, as it's more secure and I don't have to add the HTML entities filter for every single field. This means pretty much no field should use any entity encoding textformatter. I also added the Debug Extension when $config->debug is active. This way, you can use the dump function, which makes debugging templates much easier. Now, all that's left is to add a few handy global variables that all templates will have access to, and initialize an empty array to hold additional variables defined by the individual ProcessWire templates. // add the most important fuel variables to the environment foreach (['page', 'pages', 'config', 'user', 'languages', 'sanitizer'] as $variable) { $twig_env->addGlobal($variable, wire($variable)); }; $twig_env->addGlobal('homepage', $pages->get('/')); $twig_env->addGlobal('settings', $pages->get('/site-settings/')); // each template can add custom variables to this, it // will be passed down to the page template $variables = []; This includes most common fuel variables from ProcessWire, but not all of them. You could also just iterate over all fuel variables and add them all, but I prefer to include only those I will actually need in my templates. The "settings" variable I'm including is simply one page that holds a couple of common settings specific to the site, such as the site logo and site name. Page templates By default, ProcessWire loads a PHP file in the site/templates folder with the same name of the template of the current page; so for a project template/page, that would be site/templates/project.php. In this setup, those files will only include logic and preprocessing that is required for the current page, while the Twig templates will be responsible for actually rendering the markup. We'll get back to the PHP template file later, but for the moment, it can be empty (it just needs to exist, otherwise ProcessWire won't load the page at all). For our main template, we want to have a base html skeleton that all sites inherit, as well as multiple default regions (header, navigation, content, footer, ...) that each template can overwrite as needed. I'll make heavy use of block inheritance for this, so make sure you understand how that works in twig. For example, here's a simplified version of the html skeleton I used for a recent project: {# site/twig/pages/page.twig #} <!doctype html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{{ '%s | %s'|format(page.get('title'), homepage.title) }}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{{ config.urls.site }}css/main.css"> </head> <body class="{{ page.template }}"> {% block navigation %}{{ include("components/navigation.twig") }}{% endblock %} {% block header %}{{ include("components/header.twig") }}{% endblock %} {% block before_content %}{% endblock %} {% block content %} {# Default content #} {% endblock %} {% block after_content %}{% endblock %} {% block footer %}{{ include("components/footer.twig") }}{% endblock %} </body> </html> All layout regions are defined as twig blocks, so each page template can override them individually, without having to touch those it doesn't need. I'll fill the content block with default content soon, but for now this will do. Now, templates for our content types can just extend this base. This is the template for the homepage: {# site/twig/templates/pages/page--home.twig #} {% extends "pages/page.twig" %} {# No pipe-seperated site name on the homepage #} {% block title page.get('title') %} {# The default header isn't used on the homepage #} {% block header %}{% endblock %} {# The homepage has a custom slider instead of the normal header #} {% block before_content %} {{ include('sections/section--homepage-slider.twig', { classes: ['section--homepage-slider'] }) }} {% endblock %} Note that I don't do most of the actual html markup in the page templates, but in individual section templates (e.g. section--homepage-slider.twig) that can be reused across content types. More on this in the next section. We still need to actually render the template. The page template (which will be the entry point for twig) will be loaded in our _main.php, which we defined as the appendTemplateFile earlier, so it will always be included after the template specific PHP file. $template_file = 'pages/page--' . $page->template->name . '.twig'; $twig_template = file_exists($twig_main_dir . '/' . $template_file) ? $template_file : 'pages/page.twig'; echo $twig_env->render($twig_template, $variables); This function checks if a specific template for the current content type exists (e.g. pages/page--home.twig) and falls back to the default page template if it doesn't (e.g. pages/page.twig). This way, if you want a blank slate for a specific content type, you can just write a twig template that doesn't extend page.twig, and you will get a blank page ready to be filled with whatever you want. Note that it passes the $variables we initialized in the _init.php. This way, if you need to do any preprocessing or data crunching for this request, you can do it inside the PHP template and include the results in the $variables array. At this point, you can start building your default components (header, footer, navigation, et c.) and they will be included on every site that extends the base page template. Custom sections Now we've done a great deal of setup but haven't actually written much markup yet. But now that we have a solid foundation, we can add layout components very easily. For most of my projects, I use the brilliant Repeater Matrix module to set up dynamic content sections / blocks (this is not the focus of this tutorial, here's a detailed explanation). The module does have it's own built-in template file structure to render it's blocks, but since it won't work with my Twig setup, I'll create some custom twig templates for this. The approach will be the same as with the page template itself: create a "base" section template that includes some boilerplate HTML for recurring markup (such as a container element to wrap the section content in) and defines sections that can be overwritted by section-specific templates. First, let's create a template that will iterate over our the Repeater Matrix field (here it's called sections) and include the relevant template for each repeater matrix type: {# components/sections.twig #} {% for section in page.sections %} {% set template = 'sections/section--' ~ section.type ~ '.twig' %} {{ include( [template, 'sections/section.twig'], { section: section }, with_context = false ) }} {% endfor %} Note that the array syntax in the include function tells Twig to render the first template that exists. So for a section called downloads, it will look look for the template sections/section--downloads.twig and fallback to the generic sections/section.twig. The generic section template will only include the fields that are common to all sections. In my case, each section will have a headline (section_headline) and a select field to choose a background colour (section_background) : {# sections/section.twig #} {% set section_classes = [ 'section', section.type ? 'section--' ~ section.type, section.section_background.first.value ? 'section--' ~ section.section_background.first.value ] %} <div class="{{ section_classes|join(' ')|trim }}"> <section class="container"> {% block section_headline %} {% if section.section_headline %} <h2 class="section__headline">{{ section.section_headline }}</h2> {% endif %} {% endblock %} {% block section_content %} {{ section.type }} {% endblock %} </section> </div> This section template generates classes based on the section type and background colour (for example: section section--downloads section--green) so that I can add corresponding styling with CSS / SASS. The specific templates for each section will extend this base template and fill the block section_content with their custom markup. For example, for our downloads section (assuming it contains a multivalue files field download_files): {# sections/section--download.twig #} {% extends "sections/section.twig" %} {% block section_content %} <ul class="downloads"> {% for download in section.download_files %} <li class="downloads__row"> <a href="{{ download.file.url }}" download class="downloads__link"> {{ download.description ?: download.basename }} </a> </li> {% endfor %} </ul> {% endblock %} It took some setup, but now every section needs only care about their own unique fields and markup without having to include repetitive boilerplate markup. And it's still completely extensible: If you need, for example, a full-width block, you can just not extend the base section template and get a clean slate. Also, you can always go back to the base template and add more blocks as needed, without having to touch all the other sections. By the way, you can also extend the base section template from everywhere you want, not only from repeater matrix types. Now we only need to include the sections component inside the page template {# pages/page.twig #} {% block content %} {% if page.hasField('sections') and page.sections.count %} {{ include('components/sections.twig' }} {% endif %} {% endblock %} Conclusion This first part was mostly about a clean environment setup and template structure. By now you've probably got a good grasp on how I organize my twig templates into folders, depending on their role and importance: blocks: This contains reusable blocks that will be included many times, such as a responsive image block or a link block. components: This contains special regions such as the header and footer that will probably be only used once per page. sections: This will contain reusable, self-contained sections mostly based on the Repeater Matrix types. They may be used multiple times on one page. pages: High-level templates corresponding to ProcessWire templates. Those contain very little markup, but mostly include the appropriate components and sections. Depending on the size of the project, you could increase or decrease the granularity of this as needed, for example by grouping the sections into different subfolders. But it's a solid start for most medium-sized projects I tackle. Anyway, thanks for reading! I'll post the next part in a couple of days, where I will go over how to add more functionality into your environment in a scalable and reusable way. In the meantime, let me know how you would improve this setup!
  21. If each FAQ item belongs to one treatment only, I would use a Repeater instead of a page reference, so that the questions and answers can be edited in one place, on the same page where you edit the treatment itself. The repeater field is bundled in the core, but isn't active by default (go to Modules -> Core to install it). In this case, you would create a Repeater field faq containing two text fields question and answer (for example). Then you can loop over the repeater items in your frontend template and display them: foreach ($page->faq as $faq_item) { echo "<details><summary>{$faq_item->question}</summary>{$faq_item->answer}</details>"; }
  22. Sounds like a classical use case for server redirects. For example, in Apache, assuming your old subtree lived under "example.com/canines/..." and you want to move it to "example.com/dogs/...", here's a simple redirect rule that will do that, while preserving the rest of the path: RedirectMatch "^/canines/(.*)" "/dogs/$1" Example shamelessly taken from the Apache manual. Would be trivial in nginx as well. You can do the same thing in your PHP logic, but it will be slightly slower. By using the Apache redirect, the server needn't even bother ProcessWire with the request.
  23. Maybe I don't understand your problem correctly, but if you don't want to use a package manager, can't you just inject the css file for the theme directly as well? There's a CDN link on the themes page: https://unpkg.com/tippy.js@4/themes/light-border.css If you want to bundle all those files into a single dependency, I recommend Parcel, it's much simpler than webpack and you basically need no configuration for a basic compilation of JS/CSS dependencies into bundle files. I have just tried it out for a project I'm working on; this NPM script is all the config I needed: parcel build js/main.js --target browser --out-dir public/site/js --out-file bundle This will parse all code/imports in the main.js file and bundle them into a bundle.js file. It will also create a bundle.css file if you import any css.
  24. Hi @Troost, I see a couple of possible reasons. For one, you are displaying multiple fields in the projectoverzicht.php, are those fields from the homepage or from the projects index page? The $page variable will always refer to the current page, so if the loaded page is the homepage, ProcessWire will look for those fields on the homepage. If the projectoverzicht.php is also used as a standalone-page (for example, if you have a page https://your-domain.de/projectoverzicht), then the $page variable will refer to this page instead, so that is a possible error. Besides that, you are using the $project_index variable from my example, but it isn't declared anywhere, that will throw a critical error in PHP. Make sure to load the index page first!
  25. If you post the template code that you have so far it will be easier to point you in the right direction. Anyway, in order to loop over the projects in your homepage template, you'll want to (1) get the projects index page, (2) find all children with the project template and (3) render the URL and preview image field in your markup. Something like this: // use the id of your actual projects page $project_index = $pages->get(156); // use the template name of your project template $projects = $project_index->children("template=project"); echo '<ul>'; foreach ($projects as $project) { echo '<li>'; echo '<a href="' . $project->url() . '">'; // use the field name of your preview image field echo '<img src="' . $project->preview_image->url() . '" alt="' . $project->preview_image->description() . '">'; echo '</a>'; echo '</li>'; } echo '</ul>';
×
×
  • Create New...