Jump to content

Each method for a single element


Manaus
 Share

Recommended Posts

I like the syntax expressed on the ProcessWire homepage:

echo $pages->get('/')->children->each('<li><a href={url}>{title}</a>');

where html tags are generated only if the selector returns results.
In contrast to such a code:

<li><a href="<?= $page->httpUrl ?>"><?= $page->title ?></a></li>

where the external tags are generated anyway.
I read that `each` works for WireArrays, is there a method applicable to only one element? for example:

echo $pages->get(10)->someMethod('<li><a href={url}>{title}</a>');

Thanks!

Link to comment
Share on other sites

Template Engines have helpers for that very common use case. For example when using RockFrontend + Latte you can take your statement

On 7/16/2023 at 5:06 PM, Manaus said:
<li><a href="<?= $page->httpUrl ?>"><?= $page->title ?></a></li>

and simply add "n:ifcontent" to only output the whole li-tag if it contains content, meaning it will only be output if $page->title contains something:

<li n:ifcontent><a href="<?= $page->httpUrl ?>"><?= $page->title ?></a></li>

Additional to that you also have other helpers, like n:tag-if that refers not to the whole markup but only to the specific tag you put it on. That's very handy when rendering menus and some items should be linked and others should not be:

<li n:foreach="$page->children() as $item">
  <a href="..." n:tag-if="$item->viewable()">
    {$item->title}
  </a>
</li>

Which will output something like this:

<li><a href="...">Viewable page</a></li>
<li>Non-viewable page</li>
<li><a href="...">Other viewable page</a></li>
...

 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

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