Print apostrophe in python string - python

I've this view in my view
def terms(request):
d = getVariables(request,dictionary={'page_name': "Jack's Terms of Service"})
return render(request, 'jack/terms.html', d)
I'm rendering this as a page title in the templates
<title>{{ page_name }}</title>
But for some reason it prints the page_ name like this
<title>Jack's Terms of Service</title>
I don't know why it's not printing the apostrophe in the string.

Use safe. It marks a string as not requiring further HTML escaping prior to output.
<title>{{ page_name|safe }}</title>
Documentation here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

Related

Display contents of a text file in Django template

I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page.
However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string.
I've been stuck on it for two days.
Also I'm relatively new to django and self learning it
file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):
file1.write(data.split()[i] + " ")
if i%5==0 and i!=0 and i!=5:
file1.write("\n")
file1.close()
file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text
string**
<body>
{% block content %}
{{dat}}
{% endblock %}
</body>
Use the linebreaks filter in your template. It will render \n as <br/>.
use it like -:
{{ dat | linebreaks }}
from the docs:
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (<br>) and a new line followed by a
blank line becomes a paragraph break (</p>).
You can use linebreaksbr if you don't want <p> tag.
It's because in HTML newline is </br> in Python it is \n. You should convert it, before rendering
mytext = "<br />".join(mytext.split("\n"))
Depending of your needs and the file format you want to print, you may also want to check the <pre> HTML tag.

json unicode to string so i can use that in django html page

Edited :
Anybody tell me how to decode the unicode.I just want to print json unicode into my html page i developed. I got the api from heroku api.
pretty much i followed every step correctly. But the output is unicode and that i don`t know how to extract the content and display into my page.
I need to print the content. How to do that ?
my views.py
template_vars['kural'] = json.dumps(thirukural[x])
t = loader.get_template('index.html')
c = Context(template_vars)
#pprint.pprint(c)
return HttpResponse(t.render(c))
Html Page
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head><body>
<p id="p"></p>
<script type="text/javascript">
var t = {{kural|safe}}
var text = eval(t);
var p = document.getElementById("p");
p.innerHTML=t.kural;
</script>
</body></html>
</body>
</html>
It`s currently printed like this
யாதனின் யாதனின் நீங்கியான் நோதல் அதனின் அதனின் இலன்.
but in the heroku api page the sample output printed like this
{
"id": "213",
"kural": "புத்தே ளுலகத்தும் ஈண்டும் பெறலரிதே\n\nஒப்புரவின் நல்ல பிற."
}
You can see that my output doesnt have line breaks that \n . How can i do that ?
The kural variable is a dict, if you want to display kural in your view, I think you need json.
import json
template_vars['kural'] = json.dumps(thirukural[x])
I believe what you'll want to do is change that first line you show of your views code to:
template_vars['kural'] = thirukural[x].encode('ascii', 'xmlcharrefreplace')
That should change everything into HTML entities and it will end up looking something like this:
'உலகம் தழீஇய தொட்பம் மலர்தலும்\n\nகூம்பலும் இல்ல தறிவு.'

Python Variable in an HTML email in Python

How do I insert a variable into an HTML email I'm sending with python? The variable I'm trying to send is code. Below is what I have so far.
text = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1><% print code %></h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
"""
Use "formatstring".format:
code = "We Says Thanks!"
html = """\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>{code}</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
""".format(code=code)
If you find yourself substituting a large number of variables, you can use
.format(**locals())
Another way is to use Templates:
>>> from string import Template
>>> html = '''\
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>$code</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
'''
>>> s = Template(html).safe_substitute(code="We Says Thanks!")
>>> print(s)
<html>
<head></head>
<body>
<p>Thank you for being a loyal customer.<br>
Here is your unique code to unlock exclusive content:<br>
<br><br><h1>We Says Thanks!</h1><br>
<img src="http://example.com/footer.jpg">
</p>
</body>
</html>
Note, that I used safe_substitute, not substitute, as if there is a placeholder which is not in the dictionary provided, substitute will raise ValueError: Invalid placeholder in string. The same problem is with string formatting.
use pythons string manipulation:
http://docs.python.org/2/library/stdtypes.html#string-formatting
generally the % operator is used to put a variable into a string, %i for integers, %s for strings and %f for floats,
NB: there is also another formatting type (.format) which is also described in the above link, that allows you to pass in a dict or list slightly more elegant than what I show below, this may be what you should go for in the long run as the % operator gets confusing if you have 100 variables you want to put into a string, though the use of dicts (my last example) kinda negates this.
code_str = "super duper heading"
html = "<h1>%s</h1>" % code_str
# <h1>super duper heading</h1>
code_nr = 42
html = "<h1>%i</h1>" % code_nr
# <h1>42</h1>
html = "<h1>%s %i</h1>" % (code_str, code_nr)
# <h1>super duper heading 42</h1>
html = "%(my_str)s %(my_nr)d" % {"my_str": code_str, "my_nr": code_nr}
# <h1>super duper heading 42</h1>
this is very basic and only work with primitive types, if you want to be able to store dicts, lists and possible objects I suggest you use cobvert them to jsons http://docs.python.org/2/library/json.html and https://stackoverflow.com/questions/4759634/python-json-tutorial are good sources of inspiration
Hope this helps

Generating HTML documents in python

In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this?
You can use yattag to do this in an elegant way. FYI I'm the author of the library.
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
result = doc.getvalue()
It reads like html, with the added benefit that you don't have to close tags.
I would suggest using one of the many template languages available for python, for example the one built into Django (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template implementations.
I find that learning a template library helps in so many ways - whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.
Here's some simple code to get you started:
#!/usr/bin/env python
from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
It's even simpler if you have templates on disk - check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string - all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)
If you're building HTML documents than I highly suggest using a template system (like jinja2) as others have suggested. If you're in need of some low level generation of html bits (perhaps as an input to one of your templates), then the xml.etree package is a standard python package and might fit the bill nicely.
import sys
from xml.etree import ElementTree as ET
html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"
if sys.version_info < (3, 0, 0):
# python 2
ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
method='html')
else:
# python 3
ET.ElementTree(html).write(sys.stdout, encoding='unicode',
method='html')
Prints the following:
<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
There is also a nice, modern alternative: airium: https://pypi.org/project/airium/
from airium import Airium
a = Airium()
a('<!DOCTYPE html>')
with a.html(lang="pl"):
with a.head():
a.meta(charset="utf-8")
a.title(_t="Airium example")
with a.body():
with a.h3(id="id23409231", klass='main_header'):
a("Hello World.")
html = str(a) # casting to string extracts the value
print(html)
Prints such a string:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>Airium example</title>
</head>
<body>
<h3 id="id23409231" class="main_header">
Hello World.
</h3>
</body>
</html>
The greatest advantage of airium is - it has also a reverse translator, that builds python code out of html string. If you wonder how to implement a given html snippet - the translator gives you the answer right away.
Its repository contains tests with example pages translated automatically with airium in: tests/documents. A good starting point (any existing tutorial) - is this one: tests/documents/w3_architects_example_original.html.py
I would recommend using xml.dom to do this.
http://docs.python.org/library/xml.dom.html
Read this manual page, it has methods for building up XML (and therefore XHTML). It makes all XML tasks far easier, including adding child nodes, document types, adding attributes, creating texts nodes. This should be able to assist you in the vast majority of things you will do to create HTML.
It is also very useful for analysing and processing existing xml documents.
Here is a tutorial that should help you with applying the syntax:
http://www.postneo.com/projects/pyxml/
I am using the code snippet known as throw_out_your_templates for some of my own projects:
https://github.com/tavisrudd/throw_out_your_templates
https://bitbucket.org/tavisrudd/throw-out-your-templates/src
Unfortunately, there is no pypi package for it and it's not part of any distribution as this is only meant as a proof-of-concept. I was also not able to find somebody who took the code and started maintaining it as an actual project. Nevertheless, I think it is worth a try even if it means that you have to ship your own copy of throw_out_your_templates.py with your code.
Similar to the suggestion to use yattag by John Smith Optional, this module does not require you to learn any templating language and also makes sure that you never forget to close tags or quote special characters. Everything stays written in Python. Here is an example of how to use it:
html(lang='en')[
head[title['An example'], meta(charset='UTF-8')],
body(onload='func_with_esc_args(1, "bar")')[
div['Escaped chars: ', '< ', u'>', '&'],
script(type='text/javascript')[
'var lt_not_escaped = (1 < 2);',
'\nvar escaped_cdata_close = "]]>";',
'\nvar unescaped_ampersand = "&";'
],
Comment('''
not escaped "< & >"
escaped: "-->"
'''),
div['some encoded bytes and the equivalent unicode:',
'你好', unicode('你好', 'utf-8')],
safe_unicode('<b>My surrounding b tags are not escaped</b>'),
]
]
I am attempting to make an easier solution called
PyperText
In Which you can do stuff like this:
from PyperText.html import Script
from PyperText.htmlButton import Button
#from PyperText.html{WIDGET} import WIDGET; ex from PyperText.htmlEntry import Entry; variations shared in file
myScript=Script("myfile.html")
myButton=Button()
myButton.setText("This is a button")
myScript.addWidget(myButton)
myScript.createAndWrite()
I wrote a simple wrapper for the lxml module (should work fine with xml as well) that makes tags for HTML/XML -esq documents.
Really, I liked the format of the answer by John Smith but I didn't want to install yet another module to accomplishing something that seemed so simple.
Example first, then the wrapper.
Example
from Tag import Tag
with Tag('html') as html:
with Tag('body'):
with Tag('div'):
with Tag('span', attrib={'id': 'foo'}) as span:
span.text = 'Hello, world!'
with Tag('span', attrib={'id': 'bar'}) as span:
span.text = 'This was an example!'
html.write('test_html.html')
Output:
<html><body><div><span id="foo">Hello, world!</span><span id="bar">This was an example!</span></div></body></html>
Output after some manual formatting:
<html>
<body>
<div>
<span id="foo">Hello, world!</span>
<span id="bar">This was an example!</span>
</div>
</body>
</html>
Wrapper
from dataclasses import dataclass, field
from lxml import etree
PARENT_TAG = None
#dataclass
class Tag:
tag: str
attrib: dict = field(default_factory=dict)
parent: object = None
_text: str = None
#property
def text(self):
return self._text
#text.setter
def text(self, value):
self._text = value
self.element.text = value
def __post_init__(self):
self._make_element()
self._append_to_parent()
def write(self, filename):
etree.ElementTree(self.element).write(filename)
def _make_element(self):
self.element = etree.Element(self.tag, attrib=self.attrib)
def _append_to_parent(self):
if self.parent is not None:
self.parent.element.append(self.element)
def __enter__(self):
global PARENT_TAG
if PARENT_TAG is not None:
self.parent = PARENT_TAG
self._append_to_parent()
PARENT_TAG = self
return self
def __exit__(self, typ, value, traceback):
global PARENT_TAG
if PARENT_TAG is self:
PARENT_TAG = self.parent

"%" character cause Error in strings substitution with locals()

I try to substitue strings with variables using locals() in python but I can find a way to use the % character inside the string without error. Here is a concrete example :
color = colors_generator() #the function return a color
html = """<html><head>
<style>#square{color:%(color)s;width:100%;height:100%;}</style>
</head> <body> <div id="square"> </div>
</body></html>""" % locals()
print "Content-Type: text/html\n"
print html
Result : TypeError: not enough arguments for format string
The problem is the % character in 100%. How can I escape it?
escape % with %
html = """<html><head>
<style>#square{color:%(color)s;width:100%%;height:100%%;}</style>
</head> <body> <div id="square"> </div>
</body></html>""" % locals()
Virhilo has already answered your direct question, but if you find you are building quite big/complicated templates it might be worth looking at a full blown template engine instead:
http://docs.python.org/library/string.html
http://jinja.pocoo.org/
http://www.makotemplates.org/

Categories