Asset Listing - %asset_count% on type format body copy


(Mark Graham) #1

Matrix Version: 5.3.4.2

Hi all,

I’m looking for help/suggestions/ideas for how to create a sort of API endpoint that returns all event information of a particular site.
It needs to be in a pretty strict JSON format (the data is going into another system for processing) so an RSS feed is out.

I thought an Asset Listing would be ideal, and I almost got there, but I ran into an issue with adding commas between the JSON objects in the event array. I had tried to use a keyword like this: %asset_position^replace_keywords^lt:{asset_count}:,:% but the asset count keyword is only available on the page contents, not the type format. Search pages also suffer from this limitation.

I also tried using a replace keyword modifier on the %asset_listing% similar to this %asset_listing^replace_keywords^replace:string replacment:{asset_count}% but had no luck.

SSJS could be possible, but I’m not at the correct Matrix version to leverage that, unfortunately.

Any ideas?

Thanks


(Dave Lang) #2

My normal method for commas between objects in JSON style asset listings is to:

  • Create the default type format with the trailing comma
  • Create a position format for position -1 (the last one) that doesn’t have a trailing comma

It’s a bit ridiculous the asset_count keyword doesn’t work, it woul be a lot cleaner having 1 copy of the format code.

The other option is to strip the trailing comma by nesting the listing elsewhere and using %globals_asset_contents_raw:****^replace:{regex that matches trailing comma}% but that prevents you directly retrieving the listing.


(Mark Graham) #3

That’s super clever. I never thought about using position formats.

I tried it, and it’s working well. Thank you for your help!!


(Peter McLeod) #4

Hi
could also use:
%asset_position^gt:1:,:%{ /* your json…*/ }
in the type format, which might be useful if you were using differing type formats to list the data.
Thanks
Peter


(Bart Banda) #5

Yep, rather than using multiple type formats, it’s better to use a keyword modifier to inject the comma or not for the first asset being listed.


(Mark Graham) #6

The keyword for injecting the comma would only work for assets after the first, so I would have to still use the position format to stop an extra comma being used on the last asset though wouldn’t I?


(Bart Banda) #7

No, because you want a comma on the last listed asset, you just don’t want it on the first one right?

For example, consider each line below listed by the asset listing type format:

‘foo’:bar’
,‘foo’:bar’
,‘foo’:bar’
,‘foo’:bar’


(Mark Graham) #8

Of course. Makes total sense, I got confused because of my existing comma placement.

Thanks for your help guys!