How to use Kentico macros for a switch case like functionality

Ameya Kulkarni asked on August 31, 2017 20:54

I need to use kentico macro for the below scenario:-

if(condition) Then A else if(condition) Then B else if(condition) then C and so on. I find that there is no "switch" or "else if" in kentico macro, so how do I achieve the above?

Correct Answer

Peter Mogilnitski answered on September 7, 2017 22:53

Ok. You can create a custom macro and then you can have a switch in there.

Otherwise just bunch of IFs:

{% 
lib = QueryString.lib.ToLower().TrimEnd().TrimStart();
result = ""; // some default value
if(lib == "marketing roi optimization") {result ="/Marketing ROI Optimization"}
if(lib == "price promotion optimization") {result = "/Price Promotion Optimization"}
if(lib == "retail analytics") {result = "/Retail Analytics"}
return result;
#%}
1 votesVote for this answer Unmark Correct answer

Recent Answers


Peter Mogilnitski answered on August 31, 2017 22:33 (last edited on August 31, 2017 22:37)

Assuming you want to make your conditions relatively short. There is no switch but there is a "short if":

{%
x=1; y=2; z= 3;
x > y ? "Then A" : (z < y ? "Then B" : "then C")
%}
0 votesVote for this answer Mark as a Correct answer

Ameya Kulkarni answered on September 7, 2017 22:12 (last edited on September 7, 2017 22:15)

Still it is not solving my issue. I do not want to keep on nesting if and else. Most languages have a else if construct which is lacking here. I have almost 10 such statements, so is there a better solution than having to nest them inside if/else blocks.

This is what I want below:

if(QueryString.lib == "MARKETING ROI OPTIMIZATION") {"/MARKETING ROI OPTIMIZATIOn"}

else if(QueryString.lib == "Price Promotion Optimization") {"/Price Promotion Optimization"}

else if(QueryString.lib == "Retail Analytics") {"/Retail Analytics"}

And so on for 10 more statements

--

0 votesVote for this answer Mark as a Correct answer

Ameya Kulkarni answered on September 11, 2017 16:25

Great solution. Thanks.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.