Creating functions containing HTML - javascript

I'm trying to create a Coffescript function that contains common HTML for a frequently re-used object in my page. I'm passing a variable to the function with the text I want changed each time. Every time I try to compile my Coffeescript, I get this error:
[stdin]:6:5: error: unexpected identifier
<p>"text1"</p>
^^^^^
Here's my code
text1 = "Some text"
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>"text1"</p>
X
</blockquote>"
I was hoping the output would be:
Open Modal
<blockquote class="balloon" id="balloon1\">
<p>Some text</p>
X
</blockquote>
Any thoughts? I was trying to find the language for the job; maybe I should be using PHP instead? Also, I'm using Javascript because I thought the code needed to be run client-side, since I want to pass different text to the function depending on what links are clicked and when.

Since this is CoffeeScript, you can use string interpolation:
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>#{text1}</p>
X
</blockquote>"
You could also switch to single quotes in your HTML to avoid all the backslashes:
ballon1 = (text1) ->
"<a href='#balloon1'>Open Modal</a>
<blockquote class='balloon' id='balloon1'>
<p>#{text1}</p>
<a href='#close' title='Close' class='close'>X</a>
</blockquote>"
Or, if you're like me a think single quotes look funny in HTML, you could use a block string for your HTML snippet:
ballon1 = (text1) ->
"""
Open Modal
<blockquote class="balloon" id="balloon1">
<p>#{text1}</p>
X
</blockquote>
"""
A block string even lets you nicely indent the HTML for readability. This is the version I'd probably go with.

If you want string concatenation, you want the + operator:
ballon1 = (text1) ->
"Open Modal
<blockquote class=\"balloon\" id=\"balloon1\">
<p>" + text1 + "</p>
X
</blockquote>"
Change is on the fourth line.
That said, you might consider looking into templating libraries if this is something that comes up a lot. That way (with many of them) you can author your templates in an HTML editor, embedding them in your page, and not have to fuss about with quote character escaping.

Related

How to use html UTI symbol shortcuts like ™ with angularjs ng-repeat?

I'm repeating the following element:
<li ng-repeat="feature in pTab.features">
<p>{{feature.summary}}</p>
</li>
feature.summary is a string from a .txt file and contains ™ where trademark symbols should be displayed.However the page simply displays ™ as text on the page.
Looking at the W3 Reference, I thought this should display as a tradmark symbol on the page.
Does this not work with AngularJS or do I need to correct something?
Thanks!
You need to use ngBindHtml
Evaluates the expression and inserts the resulting HTML into the element in a secure way.
Code
<p ng-bind-html="feature.summary"></p>

My Django/Python Code is Not Rendering HTML <a> Tag in HTML Page

I want something similar to Twitter mentions that are turned into links but it is not working.
If we assume we have message = 'Do not forget to come with the Python book, #friend'
#function to convert #mentions to links
def mentions(message, username):
this_user_handle = reverse('mysite:profile', args=[username])
new_message = re.sub(r'(#\w+)', r"<a href= '#'>\g<0></a>", message)
new_message.replace('#', this_user_handle)
return new_message
mentions(message, 'yax') returns Do not forget to come with the Python book, <a href= '#'>#friend</a>'.
The # is not replaced and the new_message still displays as is in HTML page:
<p class= 'Post'>
{{ new_message|linebreaksbr}}
</p>
This displays this:
Do not forget to come with the Python book, <a href= '#'>#friend</a>'
Instead of:
Do not forget to come with the Python book, #friend
How do I get around this? Thank you in advance!
Replace returns a new string.
new_message = new_message.replace("#", "...")
Also Django automatically escapes HTML in templates, to disable it use the safe filter.
The content is being automatically escaped to prevent things like script injection. Use the |safe filter is you're certain that it can't contain anything nasty.
Use kwargs instead of args:
reverse('profile', kwargs={'user_name': username})
You should replace the href='' by href="" to avoid mixing things you don't want to mix (you would need to replace that in several places tho).

<br> is removed when I alert() the content of PRE tag

I want to show the content of this <pre> tag using alert():
<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain: shirzadi.ir<br>ascii: shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks: (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c: es372-irnic<br>admin-c: es372-irnic<br>tech-c: to52-irnic<br>bill-c: to52-irnic<br>nserver: wres1.irpowerweb.com<br>nserver: wres2.irpowerweb.com<br>last-updated: 2014-01-16<br>expire-date: 2017-10-08<br>source: IRNIC # Filtered<br><br>nic-hdl: es372-irnic<br>person: Ehsan Shirzadi<br>e-mail: ehsan.shirzadi#gmail.com<br>address: Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone: +985117688851<br>fax-no: +989155066372<br>source: IRNIC # Filtered<br><br>nic-hdl: to52-irnic<br>org: Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail: sales#mihannic.com<br>source: IRNIC # Filtered<br><br></pre>
when I read this content using xx = $('pre').text() and then alert(xx), the is no <br> but when I hard code this content in a variable and alert() I can see them. What is the problem here? finally I want to split the contents by <br>
Try $('pre').html() instead of text(). This should preserve < br > as well as other tags / html entities.
Edit
For completeness, as gillesc said, < br > and other tags will be stripped in alert() (since it does not support inner html). Therefore combination of .html() and replace method is required. Newline can be replaced by \n. Full code would look like this:
xx = $('pre').html().replace(/<br>/g, "\n");
alert(xx);
text() will strip the tags out so use html() instead but alert doesn't support tags so you will need to convert your <br/> before sending it to laert
See this post on how to do just that.
HTML Tags in Javascript Alert() method
Using text() keeps only the inner text, not the HTML markup.
Use html() and eventually replace each captured <br /> by the JS new line character, like said here : How replace HTML <br> with newline character "\n"
Make Like This
<pre id="MyID">This is Test <br /> This is test</pre>
and javascript code
<script>
alert(document.getElementById('MyID').innerHTML);
</script>

How do I assign a HTML string over multiple lines in Javascript?

I have to assign an HTML string through the following Javascript code. However, this seems to be possible only if I put all the HTML on one line.
This works:
var assignedhtml = "<div> <p>It's the most beautiful thing I've seen in my life </p> <p> It's watermalone </p> </div>"
This does not work:
var assignedhtml = "<div>
<p>It's the most beautiful thing I've seen in my life </p>
<p> It's watermalone </p>
</div>"
The issue is that I have too many lines my html code. In the past, I have individually removed all the \n (newline) characters. Is there a simpler way to achieve the variable assignment I intend without having to individually go through the lines and delete the newline characters?
i.e., I want to keep the html code on the right as is in the second case above, but remove the newlines before assigning it to the variable.
There's no equivalent to, for instance, PHP's heredoc but you can add backslashes to escape the hard returns:
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>";
Here's a working example: http://jsfiddle.net/9W6BS/
One more variant - use '\' symbol at the and of line
Valid code example
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>"
Also want to note, that some tools ( like webStorm or PhpStorm) allow to edit such injections in normal mode ( Alt + enter - edit HTML Fragment )
You can do it like this:
var assignedhtml = '<div>' +
'<p>It\'s the most beautiful thing I've seen in my life</p>' +
'<p>It\'s watermelon</p>' +
'</div>';

Interpreting HTML Tags in Javascript String Literal

I make an AJAX call that gives me a string within a JSON object containing text formatted like this:
Your girl was in Berkeley with a communist reader. <br> Mine was entombed within boombox and walkman. <br> I was a hoarder, but girl, that was back then. <br> The gloves are off, the wisdom teeth are out. <br> What you on about? <br> I can feel it in my bones. <br> I can feel it in my bones. <br> I'm stronger now, I'm ready for the house. <br> Such a modest mouse. <br> I can't do this alone.
I use this string to populate a div on my webpage, such that it appears like this:
<div class="lyrics-container>{{ the text in the JSON string }} </div>
However, when populating the div with that text, I get the exact string, meaning that the <br>s show up as text. I want them to actually perform their function and break the line. Is there a way to coerce the browser into interpreting HTML within a string?
I'm using Angular to grab the data and populate the div if that makes any difference.
It is not straight forward. You need to use ngBindHtml.
Controller
$scope.content = "<b>this is bold content</b>";
HTML
<div ng-bind-html="content"></div>
You'll need the following module:
http://code.angularjs.org/1.0.3/angular-sanitize.js
Be sure to declare ngSanitize as a module dependancy, like this:
var app = angular.module('angularjs-starter', ["ngSanitize"]);
You can use ng-bind-html-unsafe.
<span ng-bind-html-unsafe="content"></span>
Demo

Categories