Content
In a content file, let’s say hello.txt I have the following:
my_types: small,medium,large
I want to explode it and then use the result in a field method.
Field method
Not really that important for this issue but there is a start of a field method.
field::$methods['manipulate'] = function($field) {
return "Convert array keys to something more readable";
};
In the end the whole thing could look something like this (but working)?
$string_or_object = $item->pluck('my_types', ',')->manipulate();
How do I start with pluck?
Pluck explodes the string in the text file to an array by a needle? How should I write? I tried a few times. Items is a pages object. Am I close?
echo $item->pluck('my_types', ',');
echo $item->pluck('my_types', ',')->count();
The above give me an empty result. I expected it to print “array” or 0.
What you are looking for is probably split()
instead of pluck()
. Pluck()
is used when iterating through a collection and getting all values of a field from all pages (e.g. to generate a tag cloud), whereas split()
is used to explode the values of a string.
1 Like
Thanks! Yes that worked, kind of.
I would like some more chaining to keep my HTML clean. The split() method does only work on a $page object? Can I use split on any array somehow that is not in the object? If not, I could use PHP explode.
Something like this and make the rest in the field method:
<?php echo( $item->my_types()->manipulate() ); ?>
Not quite sure what you’re trying to get at. Split()
is a string method and so is explode, in fact, split() uses php explode anyway. Have a look at the source:
This is the field method:
field::$methods['split'] = function($field, $separator = ',') {
return str::split($field->value, $separator);
};
which uses str::split() from the toolkit:
static public function split($string, $separator = ',', $length = 1) {
if(is_array($string)) return $string;
$string = trim($string, $separator);
$parts = explode($separator, $string);
$out = array();
foreach($parts AS $p) {
$p = trim($p);
if(static::length($p) > 0 and static::length($p) >= $length) $out[] = $p;
}
return $out;
}
1 Like