Angular server side rendering template (.cshtml) parse error with escape symbols - javascript

I have C# razor *.cshtml template file and would like to use it for Angular (5) server side rendering.
C# .cshtml snippet:
#helper RenderLookupComponent()
{
<list-lookup
[data]="getLookupData('#Model.LookupSourceType')"
[lookupType]="'#Model.LookupSourceType'">
</list-lookup>
}
Everything works fine until '#Model.LookupSourceType' value is not contains escape symbol ('\'), for e.g. when #Model.LookupSourceType = 'SomeType\'
Angular template parser Error:
[error]: Template parse errors:
Parser Error: Missing expected ) at column # in [getLookupData('SomeType\')]
At first glance, it looks like ordinary issue, actually it can be solve by replacing all '\' to '\'. (#Model.LookupSourceType.Replace(#"\", #"\\")).
Q: But i believe there should be more elegant, universal approaches to solve such kind of problems.
The approach that can handles all possible scenario for different kind of escape symbols
Please share your experience

Problem was solved with using HttpUtility.JavaScriptStringEncode(Model.LookupSourceType)

Related

Put JavaScript code into a string variable

I have some data wanted to be represented using datable with jQuery. As you can see, it is easy to use by including totally two, css and javascript, files. Since, as my project requirement, neither I include any file in project folder or somewhere nor I’m able to connect to the Internet, I need to escape all javascript code into a string variable then use it between <script></script> tags. To do so, I make use of the website. I think it works pretty well since its result doesn’t yield any compiler error or warning. Whenever I include it as,
<script type=\"text/javascript\" language=\"javascript\" src=\"https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js\"></script>
it works. But when I put the content of the jquery.dataTables.min.js into a string variable by escaping via the website, I get the following error.
44th line’s the following part is hightlighted with the cross end symbol on chrome. (I’m not able to put whole code here becuase SO doesn’t permit it.)
.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},E.readyException=function(e){g.setTimeout(function(){throw e})};var $=E.Deferred();function F(){v.removeEventListener("DOMContentLoaded",F),g.removeEventListener("load",F),E.ready()}E.fn.ready=function(e){return $.then(e)["catch"](function(e){E.readyException(e)}),this},E.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--E.readyWait:E.isReady)||(E.isReady=!0)!==e&&0<--E.readyWait||$.resolveWith(v,[E])}}),E.ready.then=$.then,"complete"===v.readyState||"loading"!==v.readyState&&!v.documentElement.doScroll?g.setTimeout(E.ready):(v.addEventListener("DOMContentLoaded",F),g.addEventListener("load",F));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===T(n))for(s in i=!0,n)z(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,x(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(E(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},_=/^-ms-/,U=/-([a-z])/g;function V(e,t){return t.toUpperCase()}function X(e){return e.replace(_,"ms-").replace(U,V)}var Q=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Y(){this.expando=E.expando+Y.uid++}Y.uid=1,…………….. STACKOVERFLOW DOESN’T PERMIT LONG TEXT…………………..function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,E(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&{return g.$===E&&(g.$=xt),e&&g.jQuery===E&&(g.jQuery=bt),E},e||(g.jQuery=g.$=E),E});
What’s wrong with my idea? Cannot I apply my idea?

How can I remove ESLint parsing error from #Html.Raw(Json.Encode(Model)

To transform a server view model to a json object I am using below code in the javascript section in a rasor view.
var jsonModel = #Html.Raw(Json.Encode(Model));
The semicolon of the code is marked with a red squiggling line and the error 'ESLint encountered a parsing error' pops up (using VS 2017).
Surprisingly, when I build the project no errors show up. Also running the project locally and publishing it does not give errors and the page performs properly.
I have used syntax like:
var jsonModel = '#Html.Raw(Json.Encode(Model))';
Then the ESLint error goes away, but I get syntax errors at other code parts.
Any hints as to what causes the ESLint error and how to remove it?
Thank your for your help. Manu
You can safely ignore the parser error. Its just razor not recognizing valid syntax.
When you quote the #Html.Raw(...), you are converting the object to a string which is likely to be causing the other errors you have identified.
If you really want to avoid the parser error, you can quote it and then use JSON.parse() to convert it back to an object
var jsonModel = JSON.parse('#Html.Raw(Json.Encode(Model))');
however that is unnecessary extra overhead.

js-yaml -> Parse ruby types

I am making a Ruby console in JavaScript and thus need to accurately send Ruby object information to the renderer process. I decided to use YAML given that it is super easy to use YAML on the Ruby side and contains all information required. But I keep getting errors.
Take the following ruby:
[Test,Test.new].to_yaml
This converts to the following YAML:
---
- !ruby/class 'Test'
- !ruby/object:Test {}
When I try to parse this with JS-YAML we get the following error:
unknown tag !<!ruby/class> at line 2, column 21:
- !ruby/class 'Test'
^
So I expect this is happenning because YAML in JavaScript doesn't have Ruby types! I've seen that one solution is to create new YAML types to handle this data:
var RubyClassType = new jsyaml.Type('!ruby/class', {
kind: 'class'
});
However, in an ideal world I wouldn't have to define each individual type. In an ideal world either, all unknown types will be treated the same (e.g. as yaml sequences) or ruby wouldn't generate the odd ruby types in the first place. Can I get around this issue without having to define every Ruby type in JavaScript?
Looks like this can be handled in JS-YAML as follows: handle_unknown_types.js
Won't accept this as an answer though as a ruby-first solution would be better.

How to validate mustache template with mustache.js?

I'm using the module ejs for validating ejs template and variables that come from the admin dashboard:
try {
resolve(ejs.render(template, variables))
} catch (error) {
reject(error)
}
And if there are some issues with this template, it throws an error, and I can send it to the client.
Also, I have a mustache template to validate. I'm using the same approach:
try {
resolve(mustache.render(template, variables))
} catch (error) {
reject(error)
}
But mustache doesn't throw an error at all, and if there is no variable, it just replaces it with an empty string.
How can I solve this issue? Need to validate templates properly.
I have found a solution in this fork of the library.
Thanks to Scott it works like should.
If you're using mustache.js, there is no way to have it throw errors on undefined variables, here is an open issue. This seems to be fine according to the Mustache specification.
By default a variable "miss" returns an empty string. This can usually be configured in your Mustache library.
So if you really need to validate that there are no undefined variables, you're going to have to use another JS library for Mustache (if there is any, I'm not sure), or hope that they add the feature.
For anyone still needing a solution for this and doesn't want to/can't use another templatinh library I've created a small package to add data validation to Mustache: https://www.npmjs.com/package/mustache-validator

Simple form issue applying custom regexp (Rails 4)

I'm having some issues validating fields in Rails using simple_form gem. The issue is that, when using a custom regexp in Rails to validate in the server, everything goes fine, but the javaScript takes the whole regexp (including the tags \A or \z so it appears like wrong. For example, my validation expression is:
validates_format_of [:field1, :field2], :with => /\A(myregexp)\z/i
But in the HTML code, is sent like this, so the JavaScript doesn't take the right expression:
pattern="\A(myregexp)\z"
I know that JavaScript doesn't accept \A or either \z, but also I can't use the old tags for rails ^ or $ cause it shows an error.
Any ideas of how can I fix this?

Categories