I want to create a string variable in thymeleaf by iterating through a loop and concatenating values into this string variable. Then i want to display this string in a <span> element. What i want to achieve can be written in java as follows:
String forDisplay = "";
foreach (MyObject o : myObjectCollection) {
if (o.type == 1) { forDisplay += o.stringValue; }
}
Then in i want to put this in an html element like span. I know how to use:
<span th:each="o : ${objectCollection}" th:if="${o.type == 1}" th:text="${o.stringValue}"></span>
But this creates <span> for each of the elements that satisfy the condition. I just want to build-up my string in a th tag free section and then i just want to display my string in a single <span> element.
Ahmet, take a look at Expression Utility Objects for Strings, from Thymeleaf docs.
You have three methods for joining items:
${#strings.arrayJoin(namesArray,',')} // For Arrays
${#strings.listJoin(namesList,',')} // For Lists
${#strings.setJoin(namesSet,',')} // For Sets
These Utility Objects offers lots of cool methods for Aggregation, Calendars and etc.
Att
Here is how I join numbers into string using ", " as delimiter
<span th:each="instrumentDescriptor, iterStat : ${instrument.instrumentDescriptors}" th:text="!${iterStat.last} ? ${instrumentDescriptor.instrumentVersion} + ', ': ${instrumentDescriptor.instrumentVersion}"></span>
Related
How to display long string data from JSON as a list wise if Description string is too long. How do i split or format description Using react and typescript .
I have below JSON data:
"options": [
{
"perkType": "GIFT_CARD",
"tierRewardId": "ff592a61-3e64-474e-a3e5-cb7c14cc73e1",
"perkDescription": "**Important details about the Perk:**\n* Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)",
},
{
"tierRewardId": "0aa6b029-3179-41dd-8726-78ca7e4bfe18",
"perkType": "TOOL_RENTAL",
"perkDescription": "**Important details about the Mik Perk:**\n* Mik Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)"
}
],
already i filter the data :
const optionGift = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'GIFT_CARD');
const optionGiftCard= optionGift.map((value)=> value );
const OptionRental = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'TOOL_RENTAL',);
const OptionRentalTool= OptionRental.map((value)=> value );
component tsx code :
<div> <ul className="YourPerkOption__modelParagraph">
<li>{props.optionGiftCard[0].perkDescription}</li></ul></div>
I am trying to display a list wise data into below format
if anybody can help please .
Custom Code
If I am understanding this correctly, the first line of the perkDescription is the title (**Important details about the Mik Perk:**) and the subsequent lines are bullet points. We need to break up the string into multiple string segments and then render them to the DOM through JSX. Let's make that into it's own reusable component.
The only prop that we need is the string text.
interface PerkDescriptionProps {
text: string;
}
Our component breaks that text into an array of lines with the string.Prototype.split() method. We store the first element of the array to a variable title and the rest of the lines to another variable bullets using spread syntax. We then loop through the bullets array and put each one inside of a li element.
export const PerkDescription = ({ text }: PerkDescriptionProps) => {
const lines = text.split("\n");
const [title, ...bullets] = lines;
return (
<div className="perkDescription">
<div className="perkDescriptionTitle">{title}</div>
<ul className="perkDescriptionList">
{bullets.map((line, i) => (
<li key={i}>{line}</li>
))}
</ul>
</div>
);
};
You would call it like this:
<PerkDescription text={optionGiftCard[0].perkDescription} />
But I think you should create a Perk component that uses this PerkDescription!
I am not dealing with the asterisks here so you'll still see them in the HTML output. Are you using some some of package to parse markdown syntax?
Markdown Parsing
Your JSON is using a standardized markdown syntax to denote the list. There are already packages out there which can handle the bulleted list as well as turning the link into an a element and adding the bold styling to the title.
Using react-markdown, all you need to do is put your text inside of a ReactMarkdown component.
import ReactMarkdown from 'react-markdown'
<ReactMarkdown>{optionGiftCard[0].perkDescription}</ReactMarkdown>
You could use a RegEx to split perkDescription into an array and then map that array.
I am passing a List
errors.add(new ValidationError("Employee " + strId, "error.range," + strName +","+ intRange));
that will build a string
"Employee1","error.format,FIRST NAME,20
I want to split the message string with "," and store it in a array variable in scala template or twirl in view. I'm not really good at scala code i don't know how to store a variable in scala template nor know the syntax in splitting a string. Is there a code that can do this task in scala template?. Thank you.
<div id = "msg-menu" class = "msg-menu">
#for((key, value) <- appModel.errors) {
<div class="error-msg">
<p>#key :
#for(err <- value) {
#for(error <- err.message.split(",")) {
#Messages(error)
}
}
</p>
</div>
}
</div>
What i did was use a for loop to do it but it is not what i needed. i need to declare all the string in an array and use them as parameters on the #Messages. like:
#Messages(error[0],error[1],error[2])
In which error0 = "error.range", error1 = "FIRST NAME" and error2 = "20". In conf/message i will build an error message with the parameters
error.range = Enter {0} in {1} characters or less.
Variables are definined in twirl using #defining, in the following way:
#defining( err.message.split(",").lift ) { errors =>
...
}
The use of lift could be handy, as it helps with index out of bounds conditions where you might not know the exact number of elements in the array / collection. errors(2) will return Some("20") in your example and None if there isn't a value.
Replacing your innermost for loop with the above and hardcoding to exactly 3 parameters, you might then have something like
#defining( errors(0).getOrElse("") ) { messageId =>
#Message(messageId,errors(1).getOrElse(""),errors(2).getOrElse(""))
}
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")
I have this JSON file in a data lake that looks like this:
{
"id":"398507",
"contenttype":"POST",
"posttype":"post",
"uri":"http://twitter.com/etc",
"title":null,
"profile":{
"#class":"PublisherV2_0",
"name":"Company",
"id":"2163171",
"profileIcon":"https://pbs.twimg.com/image",
"profileLocation":{
"#class":"DocumentLocation",
"locality":"Toronto",
"adminDistrict":"ON",
"countryRegion":"Canada",
"coordinates":{
"latitude":43.7217,
"longitude":-31.432},
"quadKey":"000000000000000"},
"displayName":"Name",
"externalId":"00000000000"},
"source":{
"name":"blogs",
"id":"18",
"param":"Twitter"},
"content":{
"text":"Description of post"},
"language":{
"name":"English",
"code":"en"},
"abstracttext":"More Text and links",
"score":{}
}
}
in order to call the data into my application, I have to turn the JSON into a string using this code:
DECLARE #input string = #"/MSEStream/{*}.json";
REFERENCE ASSEMBLY [Newtonsoft.Json];
REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];
#allposts =
EXTRACT
jsonString string
FROM #input
USING Extractors.Text(delimiter:'\b', quoting:true);
#extractedrows = SELECT Microsoft.Analytics.Samples.Formats.Json.JsonFunctions.JsonTuple(jsonString) AS er FROM #allposts;
#result =
SELECT er["id"] AS postID,
er["contenttype"] AS contentType,
er["posttype"] AS postType,
er["uri"] AS uri,
er["title"] AS Title,
er["acquisitiondate"] AS acquisitionDate,
er["modificationdate"] AS modificationDate,
er["publicationdate"] AS publicationDate,
er["profile"] AS profile
FROM #extractedrows;
OUTPUT #result
TO "/ProcessedQueries/all_posts.csv"
USING Outputters.Csv();
This output the JSON into a .csv file that is readable and when I download the file all data is displayed properly. My problem is when I need to get the data inside profile. Because the JSON is now a string I can't seem to extract any of that data and put it into a variable to use. Is there any way to do this? or do I need to look into other options for reading the data?
You can use JsonTuple on the profile string to further extract the specific properties you want. An example of U-SQL code to process nested Json is provided in this link - https://github.com/Azure/usql/blob/master/Examples/JsonSample/JsonSample/NestedJsonParsing.usql.
You can use JsonTuple on the profile column to further extract specific nodes
E.g. use JsonTuple to get all the child nodes of the profile node and extract specific values like how you did in your code.
#childnodesofprofile =
SELECT
Microsoft.Analytics.Samples.Formats.Json.JsonFunctions.JsonTuple(profile) AS childnodes_map
FROM #result;
#values =
SELECT
childnodes_map["name"] AS name,
childnodes_map["id"] AS id
FROM #result;
Alternatively, if you are interested in specific values, you can also pass paramters to the JsonTuple function to get the specific nodes you want. The code below gets the locality node from the recursively nested nodes (as described by the "$..value" construct.
#locality =
SELECT Microsoft.Analytics.Samples.Formats.Json.JsonFunctions.JsonTuple(profile, "$..locality").Values AS locality
FROM #result;
Other supported constructs by JsonTuple
JsonTuple(json, "id", "name") // field names
JsonTuple(json, "$.address.zip") // nested fields
JsonTuple(json, "$..address") // recursive children
JsonTuple(json, "$[?(#.id > 1)].id") // path expression
JsonTuple(json) // all children
Hope this helps.
I would like to transform a string containing HTML tags such that all tags and properties will be in upper case (using regular expressions preferably).
For example, the following string:
'<bla>something <br/>bar</bla>'
should be changed to
'<BLA>something <BR/>bar</BLA>'
Is this possible using a single string replace with a regular expression? If so, how?
Changing just the HTML element tag names to uppercase is pretty easy. Use the callback function version of the String replace method like so:
function HtmlTagName2Upper(text) {
return text.replace(/(<\/?\w+\b)([^<>]*>)/g,
function(m0, m1, m2) {
return m1.toUpperCase() + m2;});
}
The above regex captures the tag name in $1 and all the attributes (if any) in $2. The above regex will work pretty well but does not handle attribute values having angle brackets and does not uppercase the attribute names.
Handling HTML elements having angle brackets in their attribute values and making the element attribute names uppercase is a bit more involved:
function HtmlTagAndAttributeNames2Upper(text) {
return text.replace(/(<\/?\w+\b)((?:[^<>'"]+|"[^"]*"|'[^']*')*>)/g,
function(mo0, mo1, mo2) {
mo2 = mo2.replace(/(\s+[\w\-.:]+)((?:\s*=\s*(?:"[^"]*"|'[^']*'|[\w\-.:]+))?)/g,
function(mi0, mi1, mi2) {
return mi1.toUpperCase() + mi2});
return mo1.toUpperCase() + mo2;});
}
Honestly I'm not an expert of AS3. However a work-around could be the following:
Find all the html tags through a regexp like this: <[^>]+>
Substitute all the html tags found with their upper case version (by using the toUpperCase() method).