I created a variant in SXA with a NVelocit template. In this variant I am displaying some text in an a tag: <a href="$item.Fields.Link" target="_blank">Test</a>

This works fine, but when my field "Link" is empty I don't want to show anything. So I found some information on NVelocity (not related to Sitecore though) that showed I could do this:

#if ($item.Fields.Link != "")
   <a href="$item.Fields.Link" target="_blank">Test</a>

I also tried with single quotes, with .empty, .. but nothing seems to work. I get no output anymore when doing this. If I put something after my end (just to test), that text is still shown. My field is very empty (no space or so).

Is there a way to use some NVelocity coding in SXA?

ps: I found this blog from Michael https://michaellwest.blogspot.com/2018/02/access-reference-fields-in-sxa.html where he uses #set so I guess something should be possible...

Using SXA 1.7


Thanks Dawid for telling me it was possible - it kept me searching for the solution. After a while I found out that I was comparing an object to a string.. In the output the string cast is done automatically but not for the comparison. So I ended up with a working template like this:

#set ($url = $item.Fields.Link.ToString())
#if ($url != "")
  <a href="$url" target="_blank">Test</a>

The trick was the ToString()..


Something like this works for sure as I just checked on one of my old instances:

#if ($geospatial.Distance)
    <span style="color: red">$geospatial.Distance km<span>
    <span style="color: brown">Nothing here<span>

When there will be results which don't have a $geospatial in the context the if statement will work.

SXA is not adding any custom logic to those templates, we just run Velocity.Evaluate. So maybe Sitecore have some limitation on evaluating these templates.

There is another way to achieve what you want. You can add a custom processor to ResolveVariantTokens pipeline and implement your logic in a token (C# code).

enter image description here

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.