Jump to content

explode() and sanitizer


ngrmm
 Share

Recommended Posts

I use the explode function to generate a json-feed like this

$list = $pages->get(1234)->children;
$toJSON = $list->explode(function ($item) {			
			return [
				'title' => $item->title,
				'id'    => $item->id,
				'start' => $item->summary, 
			]
		  }

But i would like to use the sanitizer on the summary field. Like this:
Obviously this can not work. But how can sanitize the summary before the output?

$list = $pages->get(1234)->children;
$toJSON = $list->explode(function ($item) {

		// $itemSummary = $sanitizer->truncate($item->summary, [
        //     'type' => 'punctuation',
        //    'maxLength' => 155,
        //    'visible' => true,
        //    'more' => '…'
        // ]);

			return [
				'title' => $item->title,
				'id'    => $item->id,
				'start' => $itemSummary, 
			]
		  }

 

 

Link to comment
Share on other sites

$item is a Page object. The "Page" class extends the "Wire" class (which all of PW's classes do), so you can access the ProcessWire instance via $item->wire and from there you can access the "Sanitizer" class via ->sanitizer:

$item->wire->sanitzer->trunc(...)

<?php
$list = $pages->get(1234)->children;
$toJSON = $list->explode(function($item) {
	$summary = $item->wire->sanitizer->truncate($item->summary, [
		'type' => 'punctuation',
		'maxLength' => 155,
		'visible' => true,
		'more' => '…',
	]);
	return [
		'title' => $item->title,
		'id'    => $item->id,
		'start' => $summary,
	];
});

Most of the time you can even do $item->sanitizer without the ->wire but I'd consider it a best practise to use ->wire because it's slightly more efficient and less error prone.

  • Like 2
  • Thanks 1
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...