Switch Case statements in template toolkit - template-toolkit

I want to implement switch case statement in Template toolkit. My code is as follows:
[% SWITCH myvar %]
[% CASE > 4 %]
Value is amplified
[% CASE < 1%]
Value is Deleted
[% CASE %]
Normal Value
[%END%]
I am getting a error message saying '<' and '>' are unexpected tokens in my script. Can Any one help me resolve this issue. I preferably dont want to use IF statements as it is reducing the speed of execution of my script. Is there any other alternative for the above.
Thanks in advance...

Template code does not support anything other than equality or in-list, as explained in the fine manual.
Having said that, I would be extraordinarily surprised if a CASE statement compiled down to something that executed faster than IF ... ELSIF ... END. In fact, I'd put money on either syntax compiling down to the exact same thing. You could also write this as a sequence of ternary operators, but I still think it would make no difference, speed-wise.
[%- IF myvar > 4;
"Value is amplified";
ELSIF myvar < 1;
"Value is Deleted";
ELSE;
"Normal Value";
END; -%]
...or...
[%- (myvar > 4) ? "Value is amplified" :
(myvar < 1) ? "Value is Deleted" : "Normal Value" -%]

Related

What am I doing wrong with my AI?

I've been programming an AI with Lua that you communicate with it in my own logical language. I stumbled across a problem and I can't seem to figure this out.
I'm trying to put y/n questions in. I pretty much said: mi=David la; (sets variable to David. la; is punctuation) la mi=David dor la; (Is 'mi' equal to 'David'?)
When I typed that into it, 'ROBO-DUDE' didn't say anything.
if v == "lol" then
local yes = true
for _,v in pairs(mode[2]) do
if v == false then
print(v)
yes = false
end
print(yes)
end
print(yes)
if yes == true then
things = things .. "jar; "
else
things = things .. "awa; "
end
end
This block of code is in a loop for the 'la' statement. 'dor' means to respond yes/no, the lexer changes it to 'lol'.
When I tested it, the code seemed to skip the dor/lol part of the loop. I went to check the lexer.
if v == "dor" then
sentence[#sentence+1] = "lol"
end
I have no clue what went wrong here. I would like somebody's help on this problem.
Nevermind. I found the problem. When I used a for loop, I used the variable 'v' for the main parser loop and the one that looped through another table/array. I believe changing the variable (any of them) will fix my issue.

How to find a specific word in string with Ruby/Rails

I got a few string like so:
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_light_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_dark_87689uiyhk
AND
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_dark_87689uiyhk
I need to check whether the strings above has one of the widesky_light, sky_light, widesky_dark and sky_dark with exactitude so I wrote this:
if my_string.match("widesky_light")
...
end
For each variant, but the problem I'm having is because sky_light and widesky_light are similar, my code is not working properly. I believe the solution to the above would be a regex, but I've spend the afternoon yesterday trying to get it to work without much success.
Any suggestions?
EDIT
A caveat: in this string (as example): TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk, the part after widesky_light, which is _87689uiyhk is optional, meaning that sometimes I have it, sometimes I don't, so a solution would not be able to count on _string_.
Looks like you just need to reorder your if statements
if my_string.match(/widesky_light/)
return 'something'
end
if my_string.match(/sky_light/)
return 'something'
end
Regex
1st regex : extract word for further checking
Here's a regex which only matches the interesting part :
(?<=_)[a-z_]+(?=(?:_|\b))
It means lowercase word with possible underscore inside, between 2 underscores or after 1 underscore and before a word boundary.
If you need some logic depending on the case (widesky, sky, light or dark), you could use this solution.
Here in action.
2nd regex : direct check if one of 4 words is present
If you just want to know if any of the 4 cases is present :
(?<=_)(?:wide)?sky_(?:dark|light)(?=(?:_|\b))
Here in action, with either _something_after or nothing.
Case statement
list = %w(
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_light_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_light_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_widesky_dark_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_sky_dark_87689uiyhk
TFjyg9780878_867978-DGB097908-78679iuhi698_trash_dark_87689uiyhk
)
list.each do |string|
case string
when /widesky_light/ then puts "widesky light found!"
when /sky_light/ then puts "sky light found!"
when /widesky_dark/ then puts "widesky dark found!"
when /sky_dark/ then puts "sky dark found!"
else puts "Nothing found!"
end
end
In this order, the case statement should be fine. widesky_dark won't match twice, for example.
Maybe something like this:
case my_string
when /_(sky_light)/
# just sky_light
when /sky_light/
# widesky_light
when /_(sky_dark)/
# just sky_dark
when /sky_dark/
# widesky_dark
else
puts "I don't like"
end

Looking for guide line about Razor syntax in asp.net mvc

i am learning asp.net mvc just going through online tutorial
1) just see <span>#model.Message</span> and #Html.Raw(model.Message)
suppose if "Hello Word" is stored in Message then "Hello Word" should display if i write statement like
<span>#model.Message</span> but i just could not understand what is the special purpose about #Html.Raw(model.Message).
what #Html.Raw() will render ?
please discuss with few more example to understand the difference well.
2) just see the below two snippet
#if (foo) {
<text>Plain Text</text>
}
#if (foo) {
#:Plain Text is #bar
}
in which version of html the tag called was introduce. is it equivalent to or what ? what is the purpose of
this tag ?
just tell me about this #:Plain Text is #bar
what is the special meaning of #: ?
if our intention is to mixing text with expression then can't we write like Plain Text is #bar
3) <span>ISBN#(isbnNumber)</span>
what it will print ? if 2000 is stored in isbnNumber variable then it may print <span>ISBN2000</span>. am i right ?
so tell me what is the special meaning of #(variable-name) why bracket along with # symbol ?
4) just see
<span>In Razor, you use the
##foo to display the value
of foo</span>
if foo has value called god then what this ##foo will print ?
5 ) see this and guide me about few more syntax given below point wise
a) #(MyClass.MyMethod<AType>())
b)
#{
Func<dynamic, object> b =
#<strong>#item</strong>;
}
#b("Bold this")
c) <div class="#className foo bar"></div>
6) see this
#functions
{
string SayWithFunction(string message)
{
return message;
}
}
#helper SayWithHelper(string message)
{
Text: #message
}
#SayWithFunction("Hello, world!")
#SayWithHelper("Hello, world!")
what they are trying to declare ? function ?
what kind of syntax it is ?
it seems that two function has been declare in two different way ? please explain this points with more sample. thanks
Few More question
7)
#{
Func<dynamic, object> b = #<strong>#item</strong>;
}
<span>This sentence is #b("In Bold").</span>
what the meaning of above line ? is it anonymous delegate?
when some one will call #b("In Bold") then what will happen ?
8)
#{
var items = new[] { "one", "two", "three" };
}
<ul>
#items.List(#<li>#item</li>)
</ul>
tell me something about List() function and from where the item variable come ?
9)
#{
var comics = new[] {
new ComicBook {Title = "Groo", Publisher = "Dark Horse Comics"},
new ComicBook {Title = "Spiderman", Publisher = "Marvel"}
};
}
<table>
#comics.List(
#<tr>
<td>#item.Title</td>
<td>#item.Publisher</td>
</tr>)
</table>
please explain briefly the above code. thanks
1) Any kind of #Variable output makes MVC automatically encode the value. That is to say if foo = "Joe & Dave", then #foo becomes Joe & Dave automatically. To escape this behavior you have #Html.Raw.
2) <text></text> is there to help you when the parser is having trouble. You have to keep in mind Razor goes in and out of HTML/Code using the semantics of the languages. that is to say, it knows it's in HTML using the XML parser, and when it's in C#/VB by its syntax (like braces or Then..End respectively). When you want to stray from this format, you can use <text>. e.g.
<ul>
<li>
#foreach (var item in items) {
#item.Description
<text></li><li></text>
}
</li>
</ul>
Here you're messing with the parser because it no longer conforms to "standard" HTML blocks. The </li> would through razor for a loop, but because it's wrapped in <text></text> it has a more definitive way of knowing where code ends and HTML begins.
3) Yes, the parenthesis are there to help give the parser an explicit definition of what should be executed. Razor makes its best attempt to understand what you're trying to output, but sometimes it's off. The parenthesis solve this. e.g.
#Foo.bar
If you only had #Foo defined as a string, Razor would inevitably try to look for a bar property because it follows C#'s naming convention (this would be a very valid notation in C#, but not our intent). So, to avoid it from continuing on we can use parenthesis:
#(Foo).bar
A notable exception to this is when there is a single trailing period. e.g.
Hello, #name.
The Razor parser realizes nothing valid (in terms of the language) follows, so it just outputs name and a period thereafter.
4) ## is the escape method for razor when you need to actually print #. So, in your example, you'd see #foo on the page in plain text. This is useful when outputting email addresses directly on the page, e.g.
bchristie##contoso.com
Now razor won't look for a contoso.com variable.
5) You're seeing various shortcuts and usages of how you bounce between valid C# code and HTML. Remember that you can go between, and the HTML you're seeing is really just a compiled IHtmlString that is finally output to the buffer.
1.
By default, Razor automatically html-encodes your output values (<div> becomes <div>). #Html.Raw should be used when you explicitly want to output the value as-is without any encoding (very common for outputting JSON strings in the middle of a <script>).
2.
The purpose of <text> and #: is to escape the regular Razor syntax flow and output literal text values. for example:
// i just want to print "Haz It" if some condition is true
#if (Model.HasSomething) { Haz It } // syntax error
#if (Model.HasSomething) { <text>Haz It</text> } // just fine
As of #:, it begins a text literal until the next line-feed (enter), so:
#if (Model.HasSomething) { #:Haz It } // syntax error, no closing '}' encountered
// just fine
#if (Model.HasSomething)
{
#:Haz It
}
3.
By default, if your # is inside a quote/double-quotes (<tr id="row#item.Id"), Razor interprets it as a literal and will not try to parse it as expression (for obvious reasons), but sometimes you do want it to, then you simply write <tr id="row#(item.Id").
4.
The purpose of ## is simply to escape '#'. when you want to output '#' and don't want Razor to interpret is as an expression. then in your case ##foo would print '#foo'.
5.
a. #(MyClass.MyMethod<AType>()) would simply output the return value of the method (using ToString() if necessary).
b. Yes, Razor does let you define some kind of inline functions, but usually you better use Html Helpers / Functions / DisplayTemplates (as follows).
c. See above.
6.
As of Razor Helpers, see http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

How can I customize this if statement?

I want to show "not selected" when #user.user_profile.prefecture.name if !#user.user_profile.prefecture.blank? was blank.
How can I customize this code?
controller
#user.profile.prefecture.name if !#user.profile.prefecture.blank?
You could use the ternary operator, which is slightly verbose:
#user.profile.prefecture.blank? ? "Not selected" : #user.profile.prefecture.name
Or, if prefecture is actually nil/not-nil, get rid of the blank?:
#user.profile.prefecture ? #user.profile.prefecture.name : "Not selected"
Finally, you could get slightly more fancy with try and ||, which most proficient Ruby developers will find quite readable:
#user.profile.prefecture.try(:name) || "Not selected"
Like this
if #user.profile.prefecture.blank?
'not selected'
else
#user.profile.prefecture.name
end
Updated:
1- An object is blank if it’s false, empty, or a whitespace string
2- Unless statement code to execute unless condition false
Answer:
"Not selected" unless !#user.profile.prefecture.blank?
Explain: #user.profile.prefecture.blank? will return true everytime that #user.profile.prefecture it’s false, empty, or a whitespace string for what the negation operator transforms that into false so the unless code section can be executed.
This approach it's very 'Ruby' to me and should be pretty easy to understand.

What is syntactically wrong with this Ruby case statement?

For some reason, the when #orgs is not working :
#orgs = Organization.all.select{|a|a.active}.count
case collection.size
when 0; "No #{entry_name.pluralize} found"
when #orgs; "#{#orgs} Businesses Returned!"
else; "#{collection.total_entries} of #{#orgs} Businesses Returned!"
end
Is this syntactically accurate? It will always return the last else statement. It never catches on the second when statement, even if #orgs == #orgs.
The actual number of #orgs = 1211.
So if I make the when statement when 1211; , it still doesn't catch. Is there a syntactical mistake here?
Did you try the following syntax ?
case collection.size
when 0 then "No #{entry_name.pluralize} found"
when #orgs then "#{#orgs} Businesses Returned!"
else "#{collection.total_entries} of #{#orgs} Businesses Returned!"
end
Your syntax isn't the issue. The logic in your conditions, I think, is all messed up.
So, #orgs does not = 1211, #orgs is a collection whose size is 1211. Big difference.
This case statement will always fail because the case is collection.size, when it should probably be #orgs.size
Let's say we changed it to be:
case #orgs.size
...
Then:
Your first when statement would start working when #orgs.size == 0
Your second when statement would still fail, because #orgs.size != #orgs - and it never will. #orgs refers to the collection of objects, while #orgs.size refers to the size of that collection. Even when #orgs == nil it will still fail because #orgs.size will throw a error because you're calling the size method on a nil object, which isn't allowed.
Your else statement is always the one called because of the problems listed above, and because the way you've written it prevent any of the other cases from ever being true.
However, that's probably still not enough. It looks to me like you're trying to return singularized or pluralized text depending on how many you have. Here's the code you probably intended to write, without the semi-colon usage:
#active_orgs = Organization.all.select{|a| a.active}
#singular_name = Organization.class.name
#plural_name = #singular_form.pluralize
case #active_orgs.size
when 1
"1 active #{#singular_name} of a total #{Organization.count} #{#plural_name}!"
else
"#{#active_orgs.count} active #{#singular_name} of a total #{Organization.count} #{#plural_name}!"
end
This will pluralize even when the count is 0, so it will say 0 active Organizations of a total 125 Organizations!
... or when the value is 1 it will say 1 active Organization of a total 125 Organziations!
If you don't want Organization capitalized, you can add a call to .downcase to take care of that.

Resources