jsviews/jsrender Converter not working on {{:...}} tag - asp.net-mvc

I am attempting to use a converter to modify a string in a jsrender template, but I can't seem to get the converter to work on a tag.
Using the example on JsRender API documentation Using converters for example, I have:
<script>
$.views.converters("upper", function(val) {
return val.toUpperCase();
});
</script>
Then in my HTML I have {{upper:Name}} which throws an error in the console: TypeError: val is undefined, and the template does not render at all.
However, if I apply the converter directly to a string like {{upper:"This should be uppercase"}} it outputs the string in uppercase as expected.
The {{:Name}} tag works fine by itself, so why isn't the converter working with it?
In case it is relevant, this is an ASP.NET-MVC project and the JSON data rendered by the template is coming from a $.post('#Url.Action(..,..)')... response. It's working perfectly until I attempt to apply the converter to the tag. Are converters not usable in this scenario?

It looks like your Name property is undefined in some case.
If you have a Name that is undefined, then {{:Name}} will render as the empty string, "" - but {{upper:Name}} will throw an error since undefined.toUpperCase() will fail.
You can investigate by breaking on thrown errors, (or by putting a break point or debugger statement in the converter) and seeing where your undefined Name is coming from.
You can also prevent the error getting thrown - and instead get error information rendered out - by any of the following techniques
write {{upper:Name onerror=true}} or {{upper:Name onerror='bad'}} (see https://www.jsviews.com/#onerror)
write
$.views.converters("upper", function(val) {
return val === undefined ? 'undefined' : val.toUpperCase();
});
write $.views.settings.debugMode(true);
and see what output you get, to investigate further about where your undefined Name is occuring.

Related

Cannot get class name from node after locating it in playwright

I have an SVG object like that:
<svg class="class-a color-green marker" .../>
In Playwright I want to get an exact list of classes of this element. I use the following code to locate it:
page.locator(".status-marker").first
The node is located properly, but when I call evaluate("node => node.className") on it, I get an empty dict, like the locator stripped all information about classes at all.
In general, it doesn't matter how I get the handle of this element, I always get an empty dict on evaluate("node => node.className").
Calling page.locator(".status-marker").first.is_visible() returns True, so the object exists.
Also if I run page.locator(".status-marker").first.evaluate("node => node.outerHTML") I'll get the full HTML of that node, that does have the class name included. I could parse that, but it would be pretty clunky solution.
I found out that I could use expect(locator).to_have_class(), but If the node has more than one class I need to put all of them for it to pass, when I care only on one of them (the other classes are dynamically generated, so I can't even know about them during tests).
Edit:
Here's some additional sample:
assert page.locator(".marker").first.evaluate("node => node.className") == {}
expect(page.locator(".marker").first).to_have_class("text-green-1")
The first assert passes - the evaluate("node => node.className") returns an empty dict. The expect() fails with the following error:
AssertionError: Locator expected to have class 'text-green-1'
E Actual value: inline pr-2 text-green-1 marker svelte-fa s-z-WEjw8Gh1FG
I've found a way to reproduce it (it happens to me in font awesome plugin for svelte):
def test_svelte_fa(page):
page.goto("https://cweili.github.io/svelte-fa/")
item = page.locator(".svelte-fa").first
assert item.is_visible()
assert "svelte-fa" in item.evaluate("node => node.className")
In your example, the className of an SVG is an SVGAnimatedString object. Which is not serializable.
If you do JSON.stringify($('.svelte-fa').className) on the browser, you will see that the value is {}.
Values returned by the evaluate function needs to be serializable.

How to send the file returned from a function over post in GatLing-Scala?

def siteNameChange():File={
for(line<-Source.fromFile("RecordedSimulation_0000_NewSiterequest2.txt").getLines())
if(line.contains("siteUrl"))
println(line)
return new File("RecordedSimulation_0000_NewSiterequest2.txt")
}
val scn = scenario("RecordedSimulation")
.exec(http("request_0")
.post(“/student/new”)
.body(RawFileBodyPart(session=>siteNameChange())).asJSON)
Hello I am a newbie to Gatling, using it for performance testing. I have a function named siteNameChange() which returns a file after doing some modifications on the file.
This function I am calling in the scenario body to send the data.
But when I am running the script I am getting scala:48:26: missing parameter type
.body(RawFileBodyPart(session=>siteNameChange())).asJSON)
Can some one please suggest whats the best thing to do this here, how to get the function return the modified file and pass the file data over the post request
body doesn't take a BodyPart (which is for multipart) parameter but a Body one.
You should be passing a RawFileBody.

what is the difference between chunk.write and chunk.render

I saw this,
chunk = chunk.write("<li>").render(bodies.block, context.push(items[i])).write("</li>\n");
Before seeing this code, i thought, render as something similar to flush, and write as something similar to "write in buffer", naturally leading to a code like below.
for loop
chunk.write("something")
end for loop
chunck.render();
But, as you can see in the first code, render is coming in between the writes. Can somebody explain the difference between these two functions.
#JAiro:
After reading your answer i tried the below code:
temaplate: You have {render} {write}
data:
{
"name": "Mick",
"render": function(c,ct,b){
chunk.render("Rendered {~n}");
},
write:function(c,ct,b){
chunk.write("Written {~n}")
}
}
Expected output:
you have Rendered
Written {~n}
Please note the {~n} after the word "Rendered" is interpreted but the {~n} after "Written" is not interpreted.
But the actual output is not same as the expected output.
Could you post a jsfiddle, that will help me in understanding.
The actual output is an empty string, which also indicate that there could be an error in the code.
The chunk.write method writes strings directly to the buffer.
On the other hand, chunk.render resolves variables contained in its argument and then writes the resulting string to the buffer.
You don't have to override the write and render function in the context.
Let me show you how it works.
Template
Hello {name}!, how are you?
Dust compiles the template to convert them in javascript. After compiling that template you are going to obtain something like:
return chk.write("Hello ").reference(ctx.get("name"), ctx, "h").write("! how are you?");
As you can see for "Hello" and "how are you?", dust uses chunk.write because it knows what it should print. However, dust doesn't know the value of {name} until it gets the context (JSON).
For that reason, it uses chunk.reference, because it will have to resolve the value of the variable name in the future. Dust is going to obtain the value of name from the JSON data.
You can read more about dust.js here:
http://linkedin.github.com/dustjs/wiki
And you can see working examples and try yours here:
http://linkedin.github.com/dustjs/test/test.html

Dart List within a Map

I have a Map in Dart (originally loaded from JSON) that looks something like this:
somevar = {
'Title': 'Some object',
'items': [{'title': 'Item 1 Title'}, {'title': 'Item 2 Title'}]
}
For some reason somevar['items'] doesn't behave quite like a list.
I get Exception: NoSuchMethodError : method not found: 'iterator' if I attempt to iterate over the list.
I also get a similar error if I try somevar['items'].length
If I manually load this "list" like this: someList = new List(somevar['items']); then it works as expected.
Any idea why this is that case, and what I'm doing wrong? For me the natural expectation would be that a "list" parsed from JSON will behave exactly like the List() object.
Never mind, seems that I had a deeper issue in my code that cause my somevar variable to be null (even though it should have the map.
Anyway, I'm marking this as solved for now so not to waste anyone's time.

Send params{} hash to another method in same controller

I am working on very complex and dynamic form where I do lot of calls to various methods to render partials depending upon values chosen for drop downs using jQuery. Problem is that after filling the form if it fails validation the form loses all the filled in values upon re-load. I got around this by sending some specific values from params{} hash to methods for my partials on re-load. But it is very cumbersome and I have large number of elements in params hash. How can send the whole params{} to another method in the same controller using jQuery?
Ok I tried this in my form:
$.post("/collections/show_selected_media_fields",{media_type: $("#collections_controller_ev0_media_id option:selected").text(), parent_form_action: "<%=params[:action]%>",ev0_manufacturer_id:"<%=params[:collections_controller_ev0].inspect%>", }, function(data) {$("#show_selected_media_fields").html(data);});
It produces following string sent as parameter:
Parameters: {"ev0_manufacturer_id"=>"{"client_asset_id"=>"", "status_id"=>"6", "server_
name"=>"", "media_id"=>"11", "serial_number"=>"", "evidence_number&quot
;=>"qwe", "notes"=>"", "model"=>"", "manufacturer_id"=>"69&quot
;, "interface"=>"SATA", "obtained_from"=>"wr", "evidence_type_id"=>"1"}
", "media_type"=>"Server", "parent_form_action"=>"quick_save"}
how can I convert this raw string to a hash in controller?
{"client_asset_id"=>
needs to be converted to
{"client_asset_id"=>"",... etc}
===========
ok I tried Tom's method. That produces the params as a string in the following shape. I tried to convert it into hash by doing an eval on it. But it errors out.
{commit=>Save, ev1_current_location_id=>, collections_controller_ev1=>{file_system=>NTFS, obtained_from=>, evidence_number=>, interface=>SAT
A, size_unit=>GB, manufacturer_id=>, encryption_version=>, media_id=>3, size=>, evidence_type_id=>3, other_encryption=>, encryption_method=>
N/A, serial_number=>, model=>, encryption_key=>}, ev0_from_location_category=>, ev0_obtained_from_email_id=>, collections_controller_ev0=>{o
btained_from=>, evidence_number=>, media_id=>1, evidence_type_id=>1, status_id=>6}, custody_action=>Create, collection=>{acquired_by=>Amande
ep Singh, custodian_id=>12, matter_id=>58, location=>sa Nose, client_id=>11, software_version=>, collection_date_time=>Fri Nov 30 14:28:06 -
0800 2012, acquisition_method=>Direct Collection, notes=>, software_id=>1}, _method=>put, utf8=>Γ£ô, ev1_current_location_category=>, ev0_cu
rrent_location_category=>, add_working_copy=>No, ev1_obtained_from_email_id=>, authenticity_token=>3vyn6057DDIyfgTnbckeh5heRTIgcVBfxtY89Krfr
/c=, ev1_existing_artifact_type=>, ev0_from_location_id=>, action=>quick_save, ev1_from_location_id=>, ev1_from_location_category=>, ev0_cur
rent_location_id=>, controller=>collections}
using .to_json and HTMLEntities gem I have gotten to a point where I have the following string. I need to convert it back to params hash. How to?
{"utf8"=>"Γ£ô","collection"=>{"acquired_by"=>"Amandeep Singh","notes"=>"","matter_id"=>"58","software_id"=>"1","acquisition_method"=>"Direct
Collection","client_id"=>"11","custodian_id"=>"0","collection_date_time"=>"Fri Nov 30 15=>52=>12 -0800 2012","software_version"=>"","locati
on"=>"sa Nose"},"ev0_current_location_id"=>"","ev1_existing_artifact_type"=>"","ev1_obtained_from_email_id"=>"","custody_action"=>"Create","
action"=>"quick_save","ev0_current_location_category"=>"","ev1_from_location_category"=>"","_method"=>"put","ev0_obtained_from_email_id"=>""
,"ev0_from_location_category"=>"","ev1_current_location_category"=>"","commit"=>"Save","controller"=>"collections","authenticity_token"=>"3v
yn6057DDIyfgTnbckeh5heRTIgcVBfxtY89Krfr/c=","ev0_from_location_id"=>"","ev1_current_location_id"=>"","collections_controller_ev0"=>{"status_
id"=>"6","media_id"=>"9","obtained_from"=>"","evidence_number"=>"","evidence_type_id"=>"1"},"collections_controller_ev1"=>{"media_id"=>"3","
encryption_key"=>"","encryption_version"=>"","size"=>"","obtained_from"=>"","encryption_method"=>"N/A","model"=>"","evidence_number"=>"","ev
idence_type_id"=>"3","size_unit"=>"GB","other_encryption"=>"","interface"=>"SATA","file_system"=>"NTFS","serial_number"=>"","manufacturer_id
"=>""},"ev1_from_location_id"=>"","add_working_copy"=>"No"}
========== edit==========
I am using the following in my view.
JSON( params[:collections_controller_ev0])
It sends following quoted string to my controller.
{"evidence_number":"","notes":"","size":"","model":"","evidence_type_id":"1","media_id":"1","obtained_from":"","status_id":"6","manufacturer_id":"","size_unit":"GB"}
I convert it into valid JSON string as below using gsub('"','"'). The output is a VALID JSON string as validated by http://jsonlint.com/ shown below.
{"evidence_number":"","notes":"123","size":"123","model":"123","evidence_type_id":"1","media_id":"1","obtained_from":"","status_id":"6","manufacturer_id":"69","size_unit":"GB"}
JSON.parse works without error on this string but does not produce a properly formed hash. It produces following:
notes123evidence_numbersize123model123evidence_type_id1media_id1obtained_fromstatus_id6size_unitGBmanufacturer_id69
Can someone please tell me how to correct this?
Try <%=raw params[:action]%> and <%=raw params[:collections_controller_ev0]%> instead
I think it will work fine.
$.post("/collections/show_selected_media_fields",{media_type: $("#collections_controller_ev0_media_id option:selected").text(), parent_form_action: <%=raw params[:action]%>,ev0_manufacturer_id:<%=raw params[:collections_controller_ev0].inspect%>, }, function(data) {$("#show_selected_media_fields").html(data);});
params is basically a hash. So you can use .to_json on it. Then in your controller you can convert it from JSON to a hash with JSON.parse().
It's generally a much better idea to use JSON if you're going to be dealing with it in Javascript or HTML at all.
The method showed in my last edit works! it produces correct hash.

Resources