1

I would like to do some quick prototyping of scriban templates but have found constantly changing the rendering variant and refresh the page to be more time consuming than I would like.

Is there a convenient way to render the templates from code? Perhaps using SPE?

1 Answer 1

2

I have found the use of SPE to be great for this kind of thing. Here is an example on how to render a scriban template.

Example: The following uses Sitecore PowerShell Extensions to render a scriban template.

$testTemplate = @"
i_item Title: {{ i_item.title }}
i_page Title: {{ i_page.title }}
"@

$item = Get-Item -Path "master:" -ID "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"

$pageContext = New-Object Sitecore.Mvc.Presentation.PageContext
$pageContext.Item = $item
[Sitecore.Mvc.Common.ContextService]::Get().Push($pageContext) > $null

$instance = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider
$scribanRenderer = $instance.GetType().GetMethod('GetService').Invoke($instance, [Sitecore.XA.Foundation.Scriban.Services.IScribanTemplateRenderer])
$scribanTemplate = $scribanRenderer.Parse($testTemplate, "testTemplate")

$renderingParams = New-Object Sitecore.XA.Foundation.Mvc.Models.RenderingWebEditingParams
$templateContext = $scribanRenderer.GetTemplateContext($false, $renderingParams)
$scriptObject = New-Object Scriban.Runtime.ScriptObject
$scriptObject.Add("i_item", $item)
$templateContext.PushGlobal($scriptObject)

$scribanRenderer.Render($scribanTemplate, $templateContext)

Example rendered output

Example: The following demonstrates how to sort item titles and generate an unordered list. The ~ was used to get rid of the extra whitespace generated by the template.

Template

{{~ titles = [] ~}}
{{~ for i_child in (sc_query i_page "query:./*[@@templatename='Primary Topic Landing']")
    if ( i_child.Title != "")
        titles = titles | array.add (sc_field i_child 'Title')
    end
end~}}
<ul>
    {{~ for i_child in titles | array.sort ~}}
    <li>{{ i_child }}</li>
    {{~ end ~}}
</ul>

Output

<ul>
    <li>About Us</li>
    <li>Consultation</li>
    <li>Contact Us</li>
    <li>test</li>
    <li>Welcome</li>
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.