Contents_raw using keywwords combined with js


(paul walker) #1

Hi Folks
From the metadata schema I am pulling in id numbers of numerous related assets as an array
Using ‘json_decode’ I am able to display a list of the id numbers but what I want to do is display the contents of the selected pages ‘assets_raw’
However, with all the code I have played around with I only seem to be able to display a string that looks like %globals_asset_contents_raw:####% rather than the content itself.
The code I am using is this;

//Get all of our assets into an array variable
const assets = %asset_metadata_page-select^json_decode^as_asset:asset_name,asset_url,asset_assetid%;
if(assets.length > 0){
    //Loop through each asset in the array
    assets.forEach(function(asset){
        //THIS RETURNS ASSET IDS DISPLAYED IN SEPARATE DIVS
        //document.write('<div class="nest-item">'+asset.asset_assetid+'</div>');
        
        //I WANT THIS TO RETURN THE CONTENTS OF EACH ASSET
        document.write('<div class="nest-item">%globals_asset_contents_raw:'+asset.asset_assetid+'%</div>');
    });
}

can anyone assist and tell me what I am doing incorrectly
Many thanks
p


(John gill) #2

From the use of document.write it seems that the JS in question is running in the browser - so by the time it executes there is no longer any server involvement so the completed %globals_asset_contents_raw:12345% keyword cannot be replaced.

The simplest change would be to run the above JavaScript as Server-side Javascript a.k.a SSJS, which would allow keywords to be processed after the code is run but before the final response is sent to the browser.

You’ll need to change the script tag to <script runat="server">, and you’ll need to replace document.write with print

<script runat="server">
//Get all of our assets into an array variable
const assets = %asset_metadata_page-select^json_decode^as_asset:asset_name,asset_url,asset_assetid%;
if(assets.length > 0){
    //Loop through each asset in the array
    assets.forEach(function(asset){
        print('<div class="nest-item">%globals_asset_contents_raw:'+asset.asset_assetid+'%</div>');
    });
}
</script>

(paul walker) #3

Thank you John for both the solution and the clear explanation of why it should be done so.
It is always a pleasure to work with more experienced practitioners that like to share their knowledge and help others.
cheers - paul walker


(Bart Banda) #4

Also have a look at https://docs.squiz.net/matrix/version/latest/developing/server-side-javascript.html#processing-order to read about the processing order when using SSJS.