I have one Contact us page with an intro blurb saying something like: Let us know how [we] can help you. The text inside the brackets needs to change based on the query string value.
For example:
If the URL is mysite.com/contact?p=product -> the text inside the
brackets is: [our technical sales rep]
If the URL is
mysite.com/contact?p=sf -> [our consultants in San Francisco office]
...
I can grab the query string value, but don't know how to use it with multiple ifs in the example above? Could you help?
For this your best bet is to create a custom macro method which will allow you to write a more robust logical statement and simply pass in the query string as the value.
The simplest approach is to pass along the actual string you want displayed in the URL as an encoded string and simply decode is when you get the value using a macro.
Your string text might look something like:
Let us know how {% QueryString.GetValue("p")|(default)"we" %} can help you.
Let us know how
{%
param = QueryString.p.ToLower().TrimEnd().TrimStart();
result = "we"; // default value
if(param == "product") {result ="our technical sales rep"}
if(param == "sf") {result = "our consultants in San Francisco office"}
if(param == "bla") {result = "bla bla bla"}
return result;
#%} can help you
Related
I have text like this:
Forecaster Strongly disagree \n\nSomething else is going to happen\n\nExample:-\n\n#:hashtag/424 \n#:hashtag/2818 ",
I need to get 424 and 2818 (which are ids) and find titles for those ids and replace #:hashtag/424 with #Title1
How do I manipulate string for this?
You can use a regular expression like this:
RegExp exp = RegExp(r'#:hashtag\/(\d+)');
String test = "Forecaster Strongly disagree \n\nSomething else is going to happen\n\nExample:-\n\n#:hashtag/424 \n#:hashtag/2818";
final matches = exp.allMatches(test);
if(matches.isNotEmpty){
print (matches.first[0]!.split('/').last);
}
//prints 424
some additional null checks will probably be nececssary depending on what you can expect from the input string
To replace the IDs you could use the replaceAllMapped method like this:
test.replaceAllMapped(exp, (match) => match[0]!.split('/').first + '/#Title1');
I am converting velocity template to Freemarker and came across this condition below
=== Velocity Code ===
#if($frm_BenefitIcons.get("$beni.benefitIconNo"))
#set($xxx = $frm_BenefitIcons.get("$beni.benefitIconNo").toString().substring(12).toUpperCase())
#else
#set($xxx = "")
#end
and I converted it to freemarker as
=== Freemarker Code ===
<#if (frm_BenefitIcons.get("${(beni.benefitIconNo)!}"))??>
<#assign xxx = frm_BenefitIcons.get("${(beni.benefitIconNo)!}")?string?substring(12)?upper_case>
<#else>
<#assign xxx = "">
</#if>
is this correct conversion ? apart from using substring.
I am getting output only xxx = "" (which is else part of condition) but not actual value (if part of the condition). Velocity code gives output value for xxx.
In short (and assuming your Configuration uses the default ObjectWrapper, or similar), if the argument to get is a String, you should write frm_BenefitIcons[key]. If frm_BenefitIcons is a java.util.Map, you can't even call get. Unless, you explicitly tell that you want to call the Java API of the object: frm_BenefitIcons?api.get(key). This last is also how you could look up with a non-String key (as the [] operator doesn't support that).
As of the conversion, I think this will be cleaner:
<#assign benefitIcon = frm_BenefitIcons[beni.benefitIconNo?c]!>
<#assign xxx = (benefitIcon != '')?then(benefitIcon[12..]?upper_case, "")>
One critical part there is that where you convert a number (beni.benefitIconNo in this case) to a string, you must use ?c, not ?string, nor "${n}". Conversion to string without ?c is subject to localized formatting, like 1234 is possibly formatted to the string "1,234", which will break the lookup for you. ?c formats for Computer audience, as opposed to for human audience, and so avoids any cultural complication.
I need to create a dynamic query based on two string parameters:
description = "This is the description"
comment = "This is the comment"
query = "insert into case(desc, comm) value(description, comment)"
Note:
there might be single quote and double quotes in both description and comment.
How do I use formatted %s to generate the query string?
Thank you very much.
UPDATE:
Thanks to Green Cloak Guy (his/her answer has minors to be corrected), the right query is:
query = f"insert into case(description, comment) value(\'{description}\', \'{comment}\')"
Use an f-string.
query = f"insert into case({description}, {comment}) value({description}, {comment})"
Don't use any type of string formatting to do actual database queries - that leads to you having a SQL Injection problem. Use a database library instead, that properly sanitizes the data.
But if all you need to do is parse some variables into a string, this is more flexible than the % formatting that other languages tend to use (and that's technically still available in python via "some_string %s %s %s" % (str1, str2, str3)")
I am stuck to find out better one between str() and format() in python
"SELECT schools.deis_income , schools.school_name,SUM(money.coin_in_amount) AS coinamount, SUM(money.note_in_amount) AS noteamount , SUM(money.coffee_coin_in_amount) AS coffeeamount , SUM(money.coin_out_amount) AS coinoutamount, SUM(money.note_out_amount) AS noteoutamount FROM money_transactions AS money JOIN school_admin_details AS sa on sa.id = money.school_admin_id JOIN schools ON schools.id=sa.school_id WHERE sa.school_id ={school_id} AND money.transaction_time BETWEEN '{start_date}' AND '{end_date}' GROUP BY schools.id".format(school_id=school_id,start_date=start_date,end_date=end_date)
I use format function here. can I use str() ?
please tell me which one give me quick result, str() or format() ???
If your question is which of this:
foo = "some text " + str(some_var) + " and some other text"
or this:
foo = "some text {} and some other text".format(var)
is "better", the general consensus is very clear: string formatting is much easier to read and maintain and the one pythonic way to go.
Now for your particular example, the answer is that both are totally wrong - unless you're ok to give full access to your database to even the most inept script kiddie. For SQL queries, the proper solution is to use prepared statements, where your db connector will take care of proper formatting and sanitizing of the values:
# assumes MySQL - for other vendors check your own
# db-api connector's doc for the correct placeholder
query = "SELECT somefield FROM mytable where somedate > %(somedate)s and something_else = %(someval)s"
cursor.execute(query, {"somedate": some_date, "someval": 42})
i want to get defect id from the url using groovy code (To build custom code in tasktop).
for example: I will have an dynamic url generated say www.xyz.com/abc/defect_123/ now I want to retrieve that letter that always starts from 17th position. and return the string
Please help..
Thanks in advance
Here are two possibilities. Please note that the "substring" option is very strict and will always start from the 16th position (what happens if the domain changes from www.xyz.com to www.xyzw.com?)
def str = 'www.xyz.com/abc/defect_123/';
def pieces = str.tokenize('/'); // prints defect_123
def from16 = str.substring(16); // prints defect_123/
println from16;
println pieces.last();
You should define this as dynamic url in UrlMappings.groovy file:
"www.xyz.com/abc/$defect_id" (controller: 'YourController', action: 'method_name')
and you can access the defect_id variable from YourController using params.defect_id