I'm trying to figure out a way to inject SSJS code in a CloudPage instead of having to copy and paste each time. That is, I have a library of functions that I want to manage centrally and include in different pages.
I know I can publish the code as a Code Resource page in CloudPages and use HTTPGet and TreatAsContent functions to access it from a landing page, but I'm wondering if it's possible to store the content as a content block and access variables or functions within it.
For example, I have a Code Snippet content block that looks like this:
<script runat=server>
function multiply(p1, p2) {
return p1 * p2;
}
</script>
And my CloudPage references the content block:
<script runat=server>
Platform.Load('core','1');
try {
Platform.Function.TreatAsContent(Platform.Function.ContentBlockByID(226637));
var calc = multiply(2,4);
Platform.Response.Write('result: ' + calc);
} catch (ex) {
Write("error message: " + ex);
}
</script>
However the script can't find the function, even though I'm injecting it on the page. I get the error:
error message: Object expected: multiply
AMPscript lets you set variables in a Content Block and then use them. For example this content block:
%%[
var @msg
set @msg = 'hello there'
]%%
...is used on the page:
%%[
TreatAsContent(ContentBlockByID(226637))
OutputLine(Concat('message: ', @msg))
]%%
and outputs:
message: hello there
Is there a way of doing something similar in SSJS?