How can I use a json member object in dojo widget - json

I am iterating a json whose format is like this
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function (jsonResults) {
arrayUtil.forEach(jsonResults.LinksMap, function (List) {
arrayUtil.forEach(List.LinksMap.entry, function (Ientry) {
var widget = new support(Ientry.Link).placeAt(authorContainer);
});
});
});
The Widget HTML template looks like
<div><span title="${title}">${title}</span></div> <br />
<div><span title="${description}">${description}</span></div> <br />
<a class="info" title="${title}" href="${url}">${title}</a><br />
I would like to use the object linkType provided in json to use a different class in the html template of the widget so if it linkType is "information" then use
<a class="info" title="${title}" href="${url}">${title}</a><br />
If it is news then use
<a class="news" title="${title}" href="${url}">${title}</a><br />

A combination of this modified template:
<div><span title="${Link.title}">${Link.title}</span></div> <br />
<div><span title="${Link.description}">${Link.description}</span></div> <br />
<a class="${className}" title="${Link.title}" href="${Link.url}">${Link.title}</a><br />
and this modified code should do the trick:
request("js/my/data/sample.json", {
handleAs: "json"}).then(function(jsonResults){ arrayUtil.forEach(jsonResults.LinksMap, function(List){arrayUtil.forEach(List.LinksMap.entry, function(Ientry){
if('information' === Ientry.linkType) Ientry.className = 'info';
else if('news link' === Ientry.linkType) Ientry.className = 'news';
var widget = new support(Ientry).placeAt(authorContainer);
});});});
But a much better idea would be implementing a postCreate method in your widget that would be able to modify widget in any way you like, after it gets constructed and just before it gets displayed.
Please refer to this guide and search for postCreate there.

Related

Convert array of links into links - React

Im new to React. Im trying to convert an array contains links into something that will show the links in order in the website.
something like this:
external_references = ["https://google.com", "https://en.wikipedia.org/wiki/Wiki"]
into something to show up in the server like this:
external_references:
https://google.com(link)
https://en.wikipedia.org/wiki/Wiki(link)
I tried to do the following code I found but it failed to work:
<span className="externalRefs">External_references: <br></br> {external_references.forEach(link => {
return new DOMParser().parseFromString(link, "text/xml");
})}</span>
you can try the map function:
<p>external_references:</p>
{external_references.map(link=>{
return <div key={link}>
<a href={link}>{link}</a>
</div>
}
}
I recomend you as a good practice using the link as a key, since each of them should be different.
just
{external_references.map((reference, i) => {
return(
<div key ={i}>
<a href ={reference}>{reference}</a>
</div>
);
})}
You can use the Array.map function.
<span className="externalRefs">External_references: <br></br>
{
external_references.map(link, i) => {
<div key ={i}>
<a href ={link}>{link}</a>
</div>
}
}
</span>

React + Next js: Cross json values in component

first I'd like to thank you for your time trying to help. I am a designer and I suck at developing stuff, so I have no other option than to scream for help.
So this is the situation:
I was asked to add an image (country flag) that's gonna be dynamic, in an element that fetches info from a JSON file with, among others, Resorts (one of the elements being its country's long name, i.e. Australia) and Countries (by long name and shortcode, i.e. Australia, au).
I need to get the country shortcode printed in the img src, but the resort array is only containing its long name.
The code:
This is the way the JSON file presents the information:
{
"Countries":[
{"name":"Australia",
"code":"au",
"continent_code":"oc",
"slug":"australia"}],
"Continents":[
{"name":"Oceania",
"code":"oc",
"slug":"oceania"}],
"Resorts":[{
"id":"1",
"resort_name":"Resort Name",
"encoded_name":"resort-name",
...
"country":"Australia",
...}]
}
And this is my file bit:
const DesktopResort = ({resort}) => (
<Link href="/resort/[resort]" as={`/resort/${resort.encoded_name}`}>
<a target='_blank' className='resort-item'>
<div className="resort">
<div className="top">
<div className="title">{resort.resort_name}</div>
<img className="logo" src="/assets/img/resort-logo-sample.png" />
<span className="info">{`${resort.ski_network} - ${resort.region}`}</span>
// Down below is the "dynamic" file call
<img className="flag-icon" src={`/assets/img/flags/${resort.country}.svg`} />
</div>
<div className="arrow"><img src="/assets/img/arrow-link.png" /></div>
</div>
</a>
</Link>
)
I know its badly done right now, for this australian resort my image src is /assets/img/flags/Australia.svg and what I would need to print is of course /assets/img/flags/au.svg
How would you do it?
Thanks again!
I'd write a little helper function to look up a country code based on the country name.
Note: you'll need to handle what should happen if the country is not found, or the code is not there. I'm just defaulting to an empty string here.
const countryCode = name => {
const country = yourData.Countries.find(country => country.name === name);
return country && country.code || '';
};
Then use this when you're passing the src to your img.
<img
className="flag-icon"
src={`/assets/img/flags/${countryCode(resort.country)}.svg`}
/>

React Render HTML object from JSON object

I have to render html object Array in React JS
Can anyone guide me how to use renderHTML function.
output of the object is something like this:
"
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("{item.albComEn}")}</div>
another variation i tried
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML("item.albComEn")}</div>
));
output i get => "item.albComEn"
or
{item.albComEn}
You can try with template strings. More info
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const items = this.state.Data.map(item => (
<div key={item._id}>{renderHTML(`${item.albComEn}`)}</div>
You can also use short syntax of React Fragments i.e. '<> </>'. Use these to bracket to write the html code. When rendered the html code will successfully compiled.
Example:
const service = [
{
htmlCode: <>
<div>
<h2>Application Screening</h2>
<br />
<br />
What you can expect from us:<br />
- Your resume will be written by a team of seasoned experts<br />
- They will make sure that your Resume presents your strong points,
achievements & key skills in a recruiter-friendly format.<br />
</div>
</>
},
]
Use inside render method as
...
render(
<div>
{service[0].htmlCode}
<div>
)
}

get innerHTML from DOM using cheerio

This Meteor server code tries to extract the innerHTML from a html string using cheerio package but the error says that the elements has no method 'size'
What am I doing wrong and how to fix it? Thanks
here is the html;
<span class='errorMsg'>some text </span>
message: (html, typeMsg) => {
let $ = cheerio.load(html);
const selection = 'span.' + typeMsg;
const elements = $(selection);
return elements.size() > 0 ? elements.get(0).innerHTML.trim() : '';
}
After few trials and errors and trying to understand the docs, which cloud benefit from some more explanations.
Option 1
const element = $(selection).eq(0);
return element ? element.text().trim() : '';
Option 2
const element = $(selection).get([0]);
return element ? element.children[0].data.trim() : '';
I used option 1 in this case.
var cheerio = require('cheerio');
var $ = cheerio.load('<b>hello</b> world');
// innerHTML
$('body').html()
// <b>hello</b> world
// outerHTML
$.html($('body'))
// <body><b>hello</b> world</body>
// innerText
$('body').text()
// hello world
docs: https://api.jquery.com/html/#html1
My HTML looked like this:
<div class="col-xs-8">
<b>John Smith</b><br />
<i>Head of Widgets</i><br />
Google<br />
Maitland, FL<br />
123-456-7890<br />
<a
href="mailto:example#example.com"
>example#example.com</a
>
</div>
I wanted to extract the inner html of the div in the context of an "each" loop, so I used this code:
$(this).html()
Which returned
<b>John Smith</b><br />
<i>Head of Widgets</i><br />
Google<br />
Maitland, FL<br />
123-456-7890<br />
<a
href="mailto:example#example.com"
>example#example.com</a
>

PartialViews - Not Using Shared Site.css in Editor/Display Templates - ASP.NET MVC 3

I'm using the JQuery UI Tabs functionality in my Open Source Project. I'm doing this to learn MVC3 (And various other technologies). Now I've got that all working. The problem is my Partial Views within each tab have links off the the relevant CRUD functionality. I've set these CRUD views up as Display and Editor Templates. Its these that are not picking up the _Layout.cshtml references to the Site.css.
EDIT START
I've found in the "Add View" scaffolding functionality that when you click the Create as a partial view box that the master page functionality disappears, ie greys out, BUT in Razor I thought if this is empty it uses the _viewstart file, which loads the_Layout?
EDIT END
Here is my Dashboard.cshtml code with the JQuery UI Tab logic:
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();
getContentTab (1);
});
function getContentTab(index) {
var url='#Url.Content("~/SiteAdmin/AjaxGetTab")/' + index;
var targetDiv = "#tabs-" + index;
var ajaxLoading = "<img id='ajax-loader' src='#Url.Content("~/Content")/ajax- loader.gif' align='left' height='28' width='28'>";
$(targetDiv).html("<p>" + ajaxLoading + " Loading...</p>");
$.ajax({
type: 'get',
url: url,
cache: false,
success: function(result) {
$(targetDiv).html(result);
}
});
}
<div id="tabs">
<ul>
<li>Transaction Type </li>
<li>Direction Type</li>
<li>User Type</li>
<li>Currency Type</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
<div id="tabs-4">
</div>
</div>
Here is my AjaxGetTab Action Method if you need to know how i decide to create tabs and create the list objects:
/// <summary>
/// AJAX action method to obtain the correct Tab to use.
/// </summary>
/// <param name="index">Tab number</param>
/// <returns>Partial View</returns>
public ActionResult AjaxGetTab(int id)
{
string partialViewName = string.Empty;
object model = null;
//--Decide which view and model to pass back.
switch (id)
{
case 1:
partialViewName = "_TransactionType";
model = db.TransactionTypes.ToList();
break;
case 2:
partialViewName = "_DirectionType";
model = db.DirectionTypes.ToList();
break;
case 3:
partialViewName = "_UserType";
model = db.UserTypes.ToList();
break;
case 4:
partialViewName = "_CurrencyType";
model = db.CurrencyTypes.ToList();
break;
case 5:
partialViewName = "_tabError";
break;
}
return PartialView(partialViewName,model);
}
At the moment I'm working on TransactionType so here is the _TransctionType.cshtml code for the PartialView:
#model IEnumerable<Accounts.Models.TransactionType>
<p>
#Html.ActionLink("Create New", "CreateTransactionType")
</p>
<table>
<tr>
<th>
Record Status
</th>
<th>
Description
</th>
<th>
Created Date
</th>
<th>
Amended Date
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.RecordStatus)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.AmendedDate)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.id })
</td>
</tr>
}
Now the "Edit" & Delete ActionLink has an EditorTemplate and the Details has a DisplayTemplate folder with the required TransactionType.cshtml Its these views which the _Layout Site.css isnt being applied to. Here is example code from the "Edit" code base:
_EditTransactionType.cshtml:
#model Accounts.Models.TransactionType
#using (Html.BeginForm())
{
#Html.EditorForModel()
<p>
<input type="submit" value="Save" />
</p>
}
And here is the TransactionType.cshtml which sits in /Views/SiteAdmin/EditorTemplate:
#model Accounts.Models.TransactionType
<fieldset>
<legend>Transaction Type</legend>
<div class="editor-label">
#Html.LabelFor(model => model.RecordStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RecordStatus)
#Html.ValidationMessageFor(model => model.RecordStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</fieldset>
Now I could just put a reference to the Site.css in each Template, but is there a cleaner way of doing this? Am I missing something?
_ViewStart is only applied to Views that are rendered, this is determined on how you render the view. E.G using RenderPartial or returning a PartialView from a controller returns only the contents (and nest partials) of the PartialView that you are targetting.
If the _LayoutFile applied to every view and every partial view then you would end up with pages like so:
<html>
<head />
<body>
<html>
<head />
<body>
<!-- Actual Partial View Content -->
</body>
</html>
</body>
</html>
When a page is rendered all of the the _layout, the view to be rendered, any partial views and any nest partials or editor/display templates are built into a single page and returned to the client so any style sheets that are referenced by the _Layout master will be applied to this now flattened heirarchy of (Partial)Views.
Have you inspected the output HTML to make sure that is as expected? It may not be a problem with the views.
I really don't see why you complicated using jqueryui tabs so much adding onclick then a switch etc.
<div id="tabs">
<ul>
<li><span>Transaction Type</span></li>
<li><span>Direction Type</span></li>
<li><span>User Type</span></li>
<li><span>Currency Type</span></li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#tabs').tabs({
spinner: '<img src="../../Content/Images/tabsppinner.gif" alt="" /> #Loading...'
});
});
</script>
Then you would just have one controller with actions defined for every tab.