Format page.num in query via sprintf or equivalent

Hello, I need to format the sorting number of pages in a query to add trailing double ceros, something I’d do with sprintf on a template as such:

sprintf('%03d', $page->num())

…but on a query I assume I need a custom method:

{{ page.num.mycustomformatter }}

…but not a field method I assume Where do I place this custom method ? Or there is a built-in alternative ?

Thanks

No, there is no custom method for that.

Since $page->num() returns either an integer or null, you cannot use a field method (that’s only possible if a method returns a field object), but have to use a page method.

Thanks,

Can I chain it as such ?

somepage.num.mycustomformatter

…and if so, how do I reference the output of num within the page method?
AFAIK $this, in a page method, refers to the page.

Or should I do something like

mycustomformatter(somepage.num)

Thanks

No, as I already wrote above, $page->num() returns either null or an integer and you can only chain methods onto objects.

You can, however, create a page method, e.g. customNum(), that you then call directly page.customNum

A simple function like in your second example should also work.

I understand now what you meant, thank you.

If I recall correctly, to create a simple function within a plugin I can do:

site/plugins/zero-trailer/index.php

<?php
function zeroTrailer($n) {
    return sprintf('%03d', $n);
}

then I should be able to do this on a query:

...
info: 'Nº {{ zeroTrailer(page.num) }}'
...

The above does not output anything. What am I missing ?

Thank you

Then it doesn’t work, so use a page method instead.

Using a page method, such as:

'pageMethods' => [
	'zerotrailer' => function ($n) {
		return sprintf('%03d', $n);	
	},

And calling it in the query as such:

{{ page.zerotrailer(page.num) }}

does work

Query language always feels a bit like the wild west.

Thank you