Laravel: How to check if route contains nothing after a slash - laravel

I have a condition to check what URL it is so I can set a proper tab class to be active.
I have code
`{{ Request::is('popular') || Request::is('/') || Request::is('category/*/popular') || Request::is('category/*') ? 'nav-active' : '' }}`
The last condition is wrong, for example when the URL is http://localhost:8000/category/goodwin/new that will still be correct, which I don't want. How can I write a condition to check if there is anything after category but only after one /
P.S. I have other conditions for new and top posts which work correctly

You can use url()->current() and then do string analysis on that. E.g. with preg_match and a regex, or by simply counting the number of slashes.
Example:
preg_match("/(.*)\/category\/(.*)\/(?!popular)(.*)/", url()->current());
The regex (.*)\/category\/(.*)\/(?!popular)(.*) checks whether the URL matches .../category/*/* except where the final * is popular.
That would allow you to do:
{{ (Request::is('popular') ||
Request::is('/') ||
Request::is('category/*/popular') ||
Request::is('category/*')) &&
preg_match("/(.*)\/category\/(.*)\/(?!popular)(.*)/", url()->current()) == 0
? 'nav-active' : '' }}
I would consider moving away from the ternary operator as this is getting quite bulky. You should probably also put this logic in the controller and just pass a variable to the view.

Related

How to have ruby conditionally check if variables exist in a string?

So I have a string from a rendered template that looks like
"Dear {{user_name}},\r\n\r\nThank you for your purchase. If you have any questions, we are happy to help.\r\n\r\n\r\n{{company_name}}\r\n{{company_phone_number}}\r\n"
All those variables like {{user_name}} are optional and do not need to be included but I want to check that if they are, they have {{ in front of the variable name. I am using liquid to parse and render the template and couldn't get it to catch if the user only uses 1 (or no) opening brackets. I was only able to catch the proper number of closing brackets. So I wrote a method to check that if these variables exist, they have the correct opening brackets. It only works, however, if all those variables are found.
here is my method:
def validate_opening_brackets?(template)
text = %w(user_name company_name company_phone_number)
text.all? do |variable|
next unless template.include? variable
template.include? "{{#{variable}"
end
end
It works, but only if all variables are present. If, for example, the template created by the user does not include user_name, then it will return false. I've also done this loop using each, and creating a variable outside of the block that I assign false if the conditions are not met. I would really, however, like to get this to work using the all? method, as I can just return a boolean and it's cleaner.
If the question is about how to rewrite the all? block to make it return true if all present variable names have two brackets before them and false otherwise then you could use something like this:
def validate_opening_brackets?(template)
variables = %w(user_name company_name company_phone_number)
variables.all? do |variable|
!template.include?(variable) || template.include?("{{#{variable}")
end
end
TL;DR
There are multiple ways to do this, but the easiest way I can think of is to simply prefix/postfix a regular expression with the escaped characters used by Mustache/Liquid, and using alternation to check for each of your variable names within the template variable characters (e.g. double curly braces). You can then use String#scan and then return a Boolean from Enumerable#any? based on the contents of the Array returned by from #scan.
This works with your posted example, but there may certainly be other use cases where you need a more complex solution. YMMV.
Example Code
This solution escapes the leading and trailing { and } characters to avoid having them treated as special characters, and then interpolates the variable names with | for alternation. It returns a Boolean depending on whether templated variables are found.
def template_string_has_interpolations? str
var_names = %w[user_name company_name company_phone_number]
regexp = /\{\{#{var_names.join ?|}\}\}/
str.scan(regexp).any?
end
Tested Examples
template_string_has_interpolations? "Dear {{user_name}},\r\n\r\nThank you for your purchase. If you have any questions, we are happy to help.\r\n\r\n\r\n{{company_name}}\r\n{{company_phone_number}}\r\n"
#=> true
template_string_has_interpolations? "Dear Customer,\r\n\r\nThank you for your purchase. If you have any questions, we are happy to help.\r\n\r\n\r\nCompany, Inc.\r\n(555) 555-5555\r\n"
#=> false

Apache freemarker template assign and compare values

I am assigning value to a variable i_type using below assign statement.
<#assign i_type>
<#if x.has("type")>
<#if x.type == "ABC">"ABC"<#else>"${x.type?lower_case}"</#if>
<#else>"pqr"</#if>
</#assign>
Then I want to assign a variable in ftl conversion as:
"final_type" : <#if i_type?has_content && i_type == "pqr">1<#else>0</#if>
But value of final_type is always coming out to be 0 in all cases.
I explicitly printed value of i_type and even though it was "pqr" but condition is always coming out to be false.
what should be changed?
Why the original example doesn't work is that you have quotation marks in <#else>"pqr"</#if>, and on the other similar places. That way the captured value itself will contain the quotation marks, because the nested content of FreeMarker directives is not expressions, instead it's just like top-level template content. So just write <#else>pqr</#if>.
Anyway, a better way to write what you did is this:
<#assign i_type =
x.has("type")?then(
(x.type == "ABC")?then(x.type, x.type?lower_case),
"pqr"
)
>
You also don't need the i_type?has_content condition in the second piece of code, since something is always assigned to i_type. (But even if in reality it isn't, you can write i_type! to default a missing value to "".) So that can be written like this:
"final_type" : ${(i_type == "pqr")?then("1", "0")}
Once I used
"final_type" : <#if i_type?has_content && i_type?eval == "pqr">1<#else>0</#if>
it worked fine.

JMeter If Controller using groovy and Or is not working

I have a script where I have some if controllers. I'm attempting to add a 4th If controller that will trigger a script failure if none of the 3 expected values is returned. It's saying one of the 3 expected values is invalid.
1st, I have a user defined variable like this:
testTool= ${__P(testTool,APPLES)}
2nd, I have these 3 If controllers with these Expressions:
${__groovy(vars.get("testTool").toUpperCase().equals("APPLES"))}
${__groovy(vars.get("testTool").toUpperCase().equals("BANANAS"))}
${__groovy(vars.get("testTool").toUpperCase().equals("PEACHES"))}
The 4th If is supposed to be triggered if the value of testTool is not one of the 3 expected values. It's Expression looks like this:
> ${__groovy( (vars.get("testTool").toUpperCase().equals("APPLES") == false ||
> vars.get("testTool").toUpperCase().equals("BANANAS") == false ||
> vars.get("testTool").toUpperCase().equals("PEACHES") == false)) }
I have also tried it this way:
> ${__groovy((!vars.get("testTool").toUpperCase().equals("APPLES") ||
> !vars.get("testTool").toUpperCase().equals("BANANAS") ||
> !vars.get("testTool").toUpperCase().equals("PEACHES")),)}
It is somehow saying APPLES is an invalid testTool. What am I doing wrong? All if controllers have the 'Interpret Condition as Variable Expression' checked.
Use the following condition in if controller
${__groovy(!(vars.get("testTool").toUpperCase().equals("APPLES"))||!(vars.get("testTool").toUpperCase().equals("BANANAS"))||!(vars.get("testTool").toUpperCase().equals("PEACHES")))}
Please let me know if it helps
You should use && operator instead of ||, see Groovy Logical Operators for detailed explanation and more information.
Your 4th expression needs to be amended to look like:
${__groovy(!(vars.get("testTool").toUpperCase().equals("APPLES")) && !(vars.get("testTool").toUpperCase().equals("BANANAS")) && !(vars.get("testTool").toUpperCase().equals("PEACHES")))}
An easier option would be using Switch Controller, from implementation and especially performance perspectives it is the optimal solution.
Add Switch Controller to your Test Plan
Use ${testTool} as the "Switch Value"
Put 4 requests as the children of the Switch Controller and name them as:
APPLES
BANANAS
PEACHES
DEFAULT
So if ${testTool} variable value will be APPLES - the APPLES sampler will be executed, if ${testTool} variable value will be BANANAS - the BANANAS sampler will be executed, etc.
If ${testTool} will not match any other children - JMeter will run DEFAULT sampler
See Selection Statements in JMeter Made Easy guide for details.

Ternary operator returns 0 instead of character string

I am in the middle of rewriting my Spring MVC application from JSP pages to Thymeleaf templates. I am however experiencing the following problem.
When I am using ternary operator with results that are of different types namely java.lang.String and java.lang.Integer the string is always presented as 0 if the condition in ternary operator is not fulfilled.
<p th:text="#{free_transfers} + ': ' + (${i ne T(java.lang.Integer).MAX_VALUE}
? ${i} : '∞')">Cumulated free transfers: ∞</p>
The resulting HTML is however
<p>Free transfers: 0</p>
if i is equal Integer.MAX_VALUE.
At first I thought that this is because of the fact that the second argument is of type int so I explicitly added the conversion to character string.
<p th:text="#{free_transfers} + ': ' + (${i ne T(java.lang.Integer).MAX_VALUE}
? ${#strings.toString(i)} : '∞')">Cumulated free transfers: ∞</p>
however this does change anything and the result is still
<p>Free transfers: 0</p>
Does anybody have any idea how to achieve the expected result
<p>Free transfers: ∞</p>
?
I have also tried these ones but without any success.
|#{free_transfers}: ${i ne T(Integer).MAX_VALUE ? #strings.toString(i) : "∞"}|
|#{free_transfers}: ${i ne T(Integer).MAX_VALUE ? i : "∞"}|
It should be all within one ${} expression also you might not need toString just use i
${i ne T(java.lang.Integer).MAX_VALUE ? i : '∞'}
There is a problem at the beginning with the order of "+" sign and ":" sign. This one works:
<p th:text="'Free transfers :'+ (${i ne T(java.lang.Integer).MAX_VALUE}
? ${i} : '∞')">Cumulated free transfers: ∞</p>
The problem was in fact in the part that provided the value of i variable. Instead of Integer.MAX_VALUE it provided 0, so no wonder it was displayed as 0.

Express JS Jade Engine If statement nested in For loop

I can't seem to find a solution to this.
I'm trying to nest a if statement inside a for loop in Jade engine (using express js).
The base code is shown below:
form
select
for obj, i in phoneModel
option(value='#{i}') #{obj.phone_model}
What I would like to do is to have a IF statement inside the for loop to check to see if a varaible "deviceIndex" is a certain value. Eg. If deviceIndex == i, then do something, else do some other thing.
I have tried the code below:
form
select
for obj, i in phoneModel
- if(phoneIndex == #{i})
option(value='#{i}') #{obj.phone_model}
- else
option(value='#{i}' selected='selected') #{obj.phone_model}
It gives the "expect indent, but got newline" error. I expect it is my placement of the if statement inside the for loop; however, I have tried just about every combination of tabs and spaces as well as putting the "option(val..." line inside a bracket on the same line as the if statement.
What's with the typeof around a boolean? And shouldn't the phone with phoneIndex == i be the one selected? Also, the point of Jade is to have much cleaner code. Tell me if this works:
form
select
for obj, i in phoneModel
option(value=i, selected=phoneIndex==i)= obj.phone_model

Resources