How to set dynamic JSON String in Thymeleaf - json

I use Thymeleaf in frontend pages, and for some reason I have to deal with i18n by i18next.js instead of spring framework.
According to the i18next-jquery introduction - using options in translation function, I write like this:
<span data-i18n="myKey" data-i18n-options='{ "WHERE": "TW" }'></span>
And there is my language resource:
{ "myKey" : "User is from {{WHERE}}." }
And html is parsed and showed like this perfectly:
<span data-i18n="myKey" data-i18n-options='{ "WHERE": "TW" }'> User is from TW. </span>
But when I set {{WHERE}} dynamically by Thymeleaf attributes, it just can't be parsed anything.
I tried
th:attrappend="data-i18n-options='{WHERE: '+ ${country} +'}'" also
th:data-i18n-options="'{WHERE: '+ ${country} +'}'",
somehow it just end up like this:
<span data-i18n="myKey" data-i18n-options="{WHERE: TW}">User is from .</span>
So I wonder that is there any idea to parse json string in Thymeleaf attribute ?
Update:
I want to share my solution,and I hope it will save someone's time :)
th:attrappend='data-i18n-options=|{ "WHERE":"${country}"}|'
or
th:data-i18n-options='|{ "WHERE":"${country}"}|'

Please try these two:
th:attrappend='data-i18n-options=|{ "WHERE":"${country}"}|'
or
th:data-i18n-options='|{ "WHERE":"${country}"}|'

Related

Apex - Generate HTML form through string

Can I create a HTML form through an apex String ? For instance, I want something like this.
String example = "<p> This is my example </p> <br/>";
But what it returns is " This is my example ", HTML tags does not have its real meaning in it. Is there any other way to achieve this ?
Thank You
What if you replace the html elements with their html entity counterparts:
String example = "<p> This is my example </p&gt <br/&gt";

IF condition with <div> in the view file of MVC

I am able to pass data to view file, but need to display them in different format with .
I try to use if statement to check the form name.
It returns error said "Operator '==' cannot be applied to operands of type 'System.Web.HtmlString' and 'string'".
Can I add blocks within IF condition? how to validate data within if condition in view file? Thank you! Here is the code:
#{ foreach (var form in #ViewBag.FormContent)
{
if (Html.Raw(form.Name) == "xyz") //pull up the title and text for the form
{
#Html.Raw(form.FormTitle)
<div class="panel-body">
<div style="height: 300px; overflow: auto; padding:15px;">
#Html.Raw(form.FormText)
</div>
</div>
}
}}
HTML.Raw returns an object that implements IHtmlString. It does not return a string. It doesn't even support ToString. Its only member is ToHtmlString(), which returns a string.
If you want to compare the output of Html.Raw with "xyz", you need to convert it to a string first. So instead of
if (Html.Raw(form.Name) == "xyz")
use something like
if (Html.Raw(form.Name).ToHtmlString() == "xyz")
Or... don't even bother with Html.Raw to begin with. Don't think you need it. Just write this:
if (form.Name == "xyz")

reHow to send a set of string in single variable through url

I want to send a value in URL that value contains more than one words i am using the given concept for example
<a href=page.jsp?variable1=value1&variable2=value2>click here</a>
Suppose in above value value1=aa and value2=bb cc dd
but in the url of page.jsp i am getting value1=aa and value2=bb only and the rest value "cc dd" is missing.
what should i do to get complete value for example value2=bb cc dd
I am giving here my code after making it more simple to focus on desire problem
`<%
MongoClient mongo = new MongoClient("localhost",27017);
DB database = mongo.getDB("studentDB");
DBCollection collection = database.getCollection("AskQuestion");
DBCursor cursor = collection.find();
String bodycontent="";
while(cursor.hasNext())
{
DBObject str=cursor.next();
bodycontent+="<table><tr><td><div> "+ str.get("TITLE") +"</div></td></tr></table>";
}
out.print(bodycontent);
%>`
For example str.get("_id") gives value "55093da9223da86a0212b364" and
str.get("TITLE") gives value "Question Title" .
Now my problem is i got value in Answer.jsp for str.get("TITLE") is only "Question" but not "Title" and i want the full value i.e Question Title.
I hope i am clear with my problem.
Try encoding your second variable and then attach it.
example: bb%20cc%20dd
<a href=page.jsp?variable1=value1&variable2=bb%20cc%20dd>click here</a>
You need to use java script for encoding your URL see this question for more details.
Passing a URL as a GET parameter in Javascript
Edit
See these answers
How to URL encode a URL in JSP?
http://www.coderanch.com/t/521213/JSP/java/encoding-URL-href-element-JSP

Ruby HTML attributes to Hash or Array

type="checkbox" name="prdCdList" value="102001174" class="bnone" newfl="Y" cpnfl="N" catcpnfl="N" eventfl="N" catcd1="102000" catcd2="102001" prdimgl="/upload/product/320_1405497216907.jpg" prdnm="Dear my volume" prdvol="3.4g" prdlndesc="Limited Pink" selprc="10000" spsalprc="0" cpnprc="0" cashptrat="0" cashpt="0" discpt="0" salstatcdnm="Available" salstatcd="PS01" prdwidth="0" prdheight="0" prddepth="0" pricestr="" price="10000" prepromote="" endpromote=""
I am currently using bunch of regexes to parse above data into a structured array or hash.
Actual tag includes much more values. Thought there must be a better way in Ruby like using split or something? There are spaces between attributes but also within certain values so..
Can any one suggest a good way to handle this type of string?
I would like the result be:
hash = {
type => "checkbox",
name => "prdCdList",
... so on.
}
or
arr = [
"checkbox",
"prdCdList",
... so on.
]
Would appreciate any advice =]
Thanks,
node.attributes.each_with_object({}) {|(k,v), acc| acc[k] = v.value }
where node is your tag.
Using Nokogiri, the attributes are already parsed for you - simply access them using []:
doc = Nokogiri::HTML.parse('<html><body><div type="checkbox" name="prdCdList" value="102001174" class="bnone" newfl="Y" cpnfl="N" catcpnfl="N" eventfl="N" catcd1="102000" catcd2="102001" prdimgl="/upload/product/320_1405497216907.jpg" prdnm="Dear my volume" prdvol="3.4g" prdlndesc="Limited Pink" selprc="10000" spsalprc="0" cpnprc="0" cashptrat="0" cashpt="0" discpt="0" salstatcdnm="Available" salstatcd="PS01" prdwidth="0" prdheight="0" prddepth="0" pricestr="" price="10000" prepromote="" endpromote=""></body></html>')
div = doc.css('div').first
div['prdnm']
# => "Dear my volume"
From the documentation:
Nokogiri::XML::Node is your window to the fun filled world of dealing
with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly
to a hash with regard to attributes. For example (from irb):
01.irb(main):004:0> node
02.=> link
03.irb(main):005:0> node['href']
04.=> "#foo"
05.irb(main):006:0> node.keys
06.=> ["href", "id"]
07.irb(main):007:0> node.values
08.=> ["#foo", "link"]
09.irb(main):008:0> node['class'] = 'green'
10.=> "green"
11.irb(main):009:0> node
12.=> link
13.irb(main):010:0>
See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.

Problem with ajax and posting non-latin characters

Posting non-latin based languages with ajax + jquery doesn't save to mysql the correct text.
What I have done is this:
I am getting multiple translated words from Google's translation api.
The ajax request is showing the correct translations for all languages.
But when i try and insert this into the db it shows up in php my admin as garbled text
I added AddDefaultCharset UTF-8 to .htaccess file on the root.
I tried setting the header in php to utf-8 and this did not work.
I have tried adding a contentType to ajax setup but this didn't work also.
I am using the following jquery code:
I am able to see the translated text sent to the save_translation.php page
var d = {"english":"<?php echo $w;?>","addwords":translated};
data = jQuery.param(d);
$.ajax({
type:"POST",
data:data,
url:"save_translation.php"
});
Each field is set to utf8_general_ci
UPDATED : responses:
Ajax post
english:thank you addwords:baie
dankie|falemnderit|شكرا|дзякуй|благодаря|gràcies|谢谢|谢谢|謝謝|hvala
vam|děkuji|tak|dank u|thank you|tänan
teid|salamat|kiitos|merci|grazas|Danke|σας
ευχαριστώ|תודה|धन्यवाद|köszönöm|þakka þér|terima kasih|go raibh maith
agat|grazie|ありがとう|감사합니다|paldies|ačiū|Ви благодарам|terima
kasih|nirringrazzjak|takk skal du ha|تشکر از
شما|dziękuję|obrigado|mulţumesc|спасибо|хвала|ďakujem|hvala|gracias|asante|tack|salamat|คุณขอบคุณ|teşekkür
ederim|спасибі|cảm ơn bạn|ddiolch 'ch|אַ דאַנק
Server Side ouput
english : thank you baie
dankie|falemnderit|شكرا|дзякуй|благодаря|gràcies|谢谢|谢谢|謝謝|hvala
vam|děkuji|tak|dank u|thank you|tänan
teid|salamat|kiitos|merci|grazas|Danke|σας
ευχαριστώ|תודה|धन्यवाद|köszönöm|þakka þér|terima kasih|go raibh maith
agat|grazie|ありがとう|감사합니다|paldies|ačiū|Ви благодарам|terima
kasih|nirringrazzjak|takk skal du ha|تشکر از
شما|dziękuję|obrigado|mulţumesc|спасибо|хвала|ďakujem|hvala|gracias|asante|tack|salamat|คุณขอบคุณ|teşekkür
ederim|спасибі|cảm ơn bạn|ddiolch 'ch|אַ דאַנק|
Each field is set to utf8_general_ci
PhpMyAdmin
thank you|baie
dankie|falemnderit|شكرا|дзÑкуй|благодарÑ|grÃ
cies|谢谢|谢谢|è¬è¬|hvala vam|dÄ›kuji|tak|dank u|thank you|tänan
teid|salamat|kiitos|merci|grazas|Danke|σας
ευχαÏιστώ|תודה|धनà¥à¤¯à¤µà¤¾à¤¦|köszönöm|þakka
þér|terima kasih|go raibh maith
agat|grazie|ã‚ã‚ŠãŒã¨ã†|ê°ì‚¬í•©ë‹ˆë‹¤|paldies|aÄiÅ«|Ви
благодарам|terima kasih|nirringrazzjak|takk skal du
ha|تشکر از
شما|dziÄ™kujÄ™|obrigado|mulÅ£umesc|ÑпаÑибо|хвала|Äakujem|hvala|gracias|asante|tack|salamat|คุณขà¸
บคุณ|teÅŸekkür ederim|ÑпаÑибі|cảm Æ¡n bạn|ddiolch
'ch|×Ö· ד×Ö·× ×§
Probably it will be enough to use JavaScript function encodeURIComponent.
If you don't add parameters manual to the URL like myUrl + '?param1=' + param1 + '&param2' + param2, but use construction myUrl + '?' + jQuery.param({param1:param1, param2:param2}) then encoding with respect of the function function encodeURIComponent will make jQuery for you. In the case all '&' characters and 'paramX=' strings will be also added for you.
But the best way to use data parameter of the jQuery.ajax method. If you use
jQuery.ajax({
url: myUrl,
data: {param1:param1, param2:param2},
//...
});
then your URL will be appended with '?param1=' + param1 + '&param2' + param2 with the corresponding encoding full from jQuery.
If my tips not helps you, please post your code example.
UPDATED: After you posted test data it was clear, that you have no problem with ajax request. You show that the data of the server look like absolutely correct. So your problem is somewhere between PHP and MYSQL. I works with no from this two products and can now not really help you. Probably information from the following link could help you string issue of utf-8 encoding with PHP and MySQL?. You can try also
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");
I wish you much success and quick solving of your problem.
Regards
P.S. In your ajax request you can directly use data: {"english":"<?php echo $w;?>","addwords":translated}. The call jQuery.param will make jQquery for you because the type of data is not a string. But it's absolutely independ on your problems.