Angular - decode string as HTML - javascript

I have some angular expressions that contain data coming from a database. Some of this data contain HTML tags in the database and should be decoded as such in the HTML.
Javascript function:
vm.showTechnicalSupport = function () {
$http.get('Navigation/GetTechSupportInformation').success(function (data) {
vm.techSupportHours = data.techSupportHours;
})
}
HTML:
<span>{{ vm.techSupportHours}}</span>
The problem is techSupportHours is displaying raw HTML tags instead of rendering markup.
For example, there are br tags being displayed visibly on the page. Is there a way to modify my angular expression to decode this data?

There is a directive called ng-bind-html which is what you are looking for.
So just change your html template to be:
<span ng-bind-html="vm.techSupportHours"></span>

Related

Re-Render some data on the same template

I have a scenario where-in by-default I would be rendering some data from JSON on my JSP page. Now, I want to achieve a use-case wherein when I click on some menu-item it would trigger a function and that should in response update the template with the relevant data.
So for initial loading I am loading the data from JSON using:
$.getJSON( "/somelocation/test.json", function( data ) {
console.log(data); //json output
var template = $.templates("#theContent");
var htmlOutput = template.render(data, {selectedValue: "abc"});
$("#mainBody").html(htmlOutput);
});
Now I write the same logic in a function which will be triggered on the menu item click then on the JSP page I just see "#theContent" as an output. Can you please suggest what might be an issue.
If you pass a string to $.templates(someString), then JsRender will first attempt to treat it as a jQuery selector. If jQuery is loaded and the selector does return a script element for a template then that template will be used.
If the string is not valid selector or does not return a script element for a template block, then JsRender will fall back on treating the string as template markup.
You can test in the context of your code whether $("#theContent") does return a non-empty jQuery object. ($("#theContent").length === 1). It looks as if in your code it is not finding a script element with ID "theContent".

How to render the quill js content using go buffalo framework

The options that i am aware of are,
Get the content of the quilljs from getContents api which gives the JSON structure. I can post this to server and store it in server.
Get the innerHTML of the div which is passed to Quill editor and store it.
Approach 1:
While displaying it back I need to write the content in my buffalo template in a variable like
<script> var contentJSON = "<%= content %>"</script>
Then once the page loaded I need to set the contents like quillInstance.setContents(contentJSON)
Approach 2:
Incase the request is compromised then the html may contain scripts unescaped. So if I try like this
c.Set("getContent", func(content string) template.HTML {
return template.HTML(html.EscapeString(content))
})
This escapes all the html entities. So all the div, styles introduced by quill js also gone with this. So the whole content looks just like a plain string.
Whats the right approach in storing the content? I am looking for a way to get this rendered in the server.
Finally i end with the following,
Helpers: render.Helpers{
"quil_for": func(content string) template.HTML {
content = strings.ReplaceAll(content, "<script>", "<script>")
content = strings.ReplaceAll(content, "<a>", "<a>")
content = strings.ReplaceAll(content, "</a>", "</a>")
content = strings.ReplaceAll(content, "</script>", "</script>")
return template.HTML(content)
},
},
instead of this
c.Set("getContent", func(content string) template.HTML {
return template.HTML(html.EscapeString(content))
})
This escapes only the script and the anchor tag and the res of html as it is.

Angular $http.get query returning html data doesn't display as normal html.. Instead it display as text in website ..

Basically my problem is that when i fetch data using $http.get method of the AngularJS , the Json encoded data which is printed by the PHP doesnt render in the website instead it shows as plain text.. for ex when PHP prints <h3 class=\"someclass\">Hello World<\/div>" and also simultaneously i try to parse the JSON using JSON.parse but it gives me Syntax Error: Unexpected token o . Basically the received HTML markup is not rendered.. Its just as plain text..
See below:
The h3 tag that i rectangled in black doesn't render in the page. Even in the source you can see its not as a markup but as a plain text.
There is a pretty good answer on escaping/not escaping HTML in angular here: https://stackoverflow.com/a/19417443/402551
It is a security feature that text injected into the DOM is not parsed as HTML, which saves you against some XSS attacks and the like. You have to manually ensure that it is rendered, so you need to think about the security implications yourself. Please familiarize yourself with XSS mechanisms and sanitize your input, before you bypass the escaping.
In general, Angular is designed in a way that you do not render any HTML server-side, just supply your frontend with the data and render there. This way, you won't have most of these problems. Please review, whether you can change that in your project.
Use ng-bing-html to escape HTML content from the response,
While getting the response do as below,
$scope.temp_variable=$sce.trustAsHtml(response);
In your HTML display the value like this,
<div>
<span ng-bind-html="temp_variable"></span>
</div>
To print an html data, Ned to include sanitize Module first
http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-sanitize.js
Then create a filter
Rapp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
Then write the html as shown below
<span ng-bind-html="myWelcome | unsafe"></span>

JavaScript jade modal variable

Folks,
I am trying to dynamically generate a modal. How would I find this piece of text and swap in the values?
I have a label, which I would like to dynamically set the content to from the table. Whats the proper way to find and replace the | .emailAddress ?
.modal-body
h3
span.label.label-info Email
| .emailAddress
script.
var $modal = $('#mymodal')
, $titleField = $modal.find('.modal-title')
, $emailField = $modal.find('| .emailAddress');
$('body').on('show.bs.modal', '.modal', function () {
var mid = $(event.target).closest('tr').data('id');
var email = $(event.target).closest('tr').data('email');
$titleField.text(email);
$emailField.text(email);
});
You don't explain how you're using Jade, there are two versions:
server side, your client get an generated HTMl
client side, you compile your Jade template to JavaScript and load the JS file in the client.
For your problem there are two solutions:
You change the HTML which is already generated because the user action can be triggered after the page is loaded. (this is how your solution looks like, but this has nothing to do with Jade!)
You reload the Jade template: remove the old template from the DOM and pass the use data (from the modal action) to the new template, only works for solution 2.
But maybe your error is this selector, which is not correct:
$modal.find('| .emailAddress');
try this:
$modal.find('.emailAddress');

Safely Using JSON with html inside of the JSON in Django Templates

How do you safely render JSON data in a django webapp?
On the server in django I generate JSON data and then render that JSON data in a django template. The JSON occasionally contains snippets of html. Most of the time, that's fine, however if the </script> tag is inside the JSON data when it is rendered, it destroys the surrounding javascript.
For example...
On the server, in python I'll have this:
template_data = {
'my_json' : '[{"my_snippet": "<b>Happy HTML</b>"}]'
}
# pass the template data to the django template
return render_to_response('my_template.html', template_data, context_instance = c)
And then in the template:
<script type="text/javascript">
var the_json = {{my_json|safe}};
</script>
... some html ...
The resulting html works fine and looks like this:
<script type="text/javascript">
var the_json = [{"my_snippet": "<b>Happy HTML</b>"}];
</script>
... some html ...
However, you run into problems when, on the server, the JSON looks like this:
template_data = {
'my_json' : '[{"my_snippet": "Bad HTML</script>"}]'
}
return render_to_response('my_template.html', template_data, context_instance = c)
Now, when it's rendered, you'll get:
<script type="text/javascript">
var the_json = [{"my_snippet": "Bad HTML</script>"}];
</script>
... some html ...
The closing script tag within the JSON code is treated as closing the entire script block. All of your javascript will then break.
One possible solution is to check for </script> when passing the template data to the template, but I feel like there is a better way.
Safely insert the JSON as a string, and then call JSON.parse on it
Use escapejs instead of safe. It is designed for outputting to JavaScript.
var the_json = '{{my_json|escapejs}}';
To get a JavaScript object you then need to call JSON.parse on that string. This is always preferable than dumping a JSON-encoding into your script and evaluating it directly, for security reasons.
A useful filter to get python objects directly to the client that I use is this:
#register.filter
def to_js(value):
"""
To use a python variable in JS, we call json.dumps to serialize as JSON server-side and reconstruct using
JSON.parse. The serialized string must be escaped appropriately before dumping into the client-side code.
"""
# separators is passed to remove whitespace in output
return mark_safe('JSON.parse("%s")' % escapejs(json.dumps(value, separators=(',', ':'))))
And use it like:
var Settings = {{ js_settings|to_js }};

Categories

Resources