I am a new user of Jinja2.I am trying to use Jinja2 template engine with python sphinx. I want to add some loops and variables from jinja to create a html file . My .rst file uses a sphinx template and I am just writing the below line in the file :
{{ a_variable }}
Where do I need to specify the value of this variable (ex. a_variable="hello world") so that "hello world" is displayed in the html file as text.
You specific the variable in your render command.
template = jinja2.Environment(loader=jinja2.FileSystemLoader(["./templates/WebPages"])).get_template("WebPage.html")
return template.render(SomeVariable='something')
Hope this helps!
Related
I'm trying to create a Django form with a filefield to upload a pdf based on a model.
#models.py
class ProductionRequest(models.Model):
...
contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/')
...
I can upload the file and save it in my object, but when I try to show the file in my template with this code
{{ prod_req.contract_file }}
it only show me the path to the file
"contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ?
Plus : when I try to open the file from Django admin, with this link
Contract file (PDF) : Currently: contracts/file_uploaded.pdf
I don't show me the file, i got this :
Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/
How can I access to my file ?
It works just like a Python file. So, the way you have just refers to a file object.
To get the text, you need to use f.read(). So, in your template, instead of
{{ prod_req.contract_file }}
use
{{ prod_req.contract_file.read }}
BUT, note that calling read moves the cursor to the end of the file. The first time you call read on a file, it returns all the text. The second time, it returns nothing. This is only a problem if you need the text twice, but in that case, store the text directly on the context object.
Let me know if anything was unclear.
Now I am using pyramid framework and mako template engine. And want to add i18n feature.
There is no problem if I write this code:
myprj/templates/index.html
<h1>${_('Home')}</h1>
It can rightly read the compiled .mo file and show the translated message from some kinds of languages.
But if I use it like this:
myprj/templates/show.html
${_context.detail_panel(order)}
And write code in this file:
myprj/templates/_detail_panel_a.html
<h1>${_('Detail')}</h1>
It shows this error:
Traceback (most recent call last):
...
File "/mypath/myprj/templates/_detail_panel_a.html", line 5, in render_body
<h1>${_('\u934j\u29jd\u01ld\u9dk3')}</h1>
MakoRenderingException:
Traceback (most recent call last):
...
File "/mypath/myprj/templates/_detail_panel_a.html", line 5, in render_body
<h1>${_('\u934j\u29jd\u01ld\u9dk3')}</h1>
UnboundLocalError: local variable '_' referenced before assignment
I registered _ event in this way:
myprj/myprj/subscribers.py
def add_renderer_globals(event):
request = event['request']
event['_'] = request.translate
event['localizer'] = request.localizer
And call it in __init__.py file:
myprj/myprj/__init__.py
config.add_subscriber('myprj.subscribers.add_renderer_globals', 'pyramid.events.BeforeRender')
I don't know why it is not work when I using render template page. I think if it necessary to define the _ event not only request.translate, but also something like render method.
But after I check the official document, I don't know how to do.
How to do?
You should refer to http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/templates/mako_i18n.html
It should help you complete translation. As you can see, you should add a tsf global variable (from line 11 onwards in the resource above).
Also you might want to check your rendering of templates with mako, since from what I read you are placing a mako placeholder into an html file. I suggest this resource: http://docs.pylonsproject.org/projects/pyramid_mako/en/latest/
Note: if you add html tags into your msg strings, use | n filter into your mako placeholders as in ${ | n}.
Check these out, I would be happy to help if you had further problems, I just implemented internationalization on my Pyramid app
I want to add set of css files to head. For instance,
python file:
modules.py
class SomeModule(tornado.web.UIModule):
def css_files(self):
return [self.handler.static_url('css/modules/some-module.css'),]
def render(self, some_data=None):
result = ''
if some_data is not None:
"""to do something with data"""
return result
server.py
app = Application(
...
ui_module=modules
...
)
template file:
...
{% module SomeModule(some_data=put_data_here) %}
As the result, I see only data that were returned from render. But css files weren't set between head tags.
What's the result of the template file depends on how you generate the template file. As far as I can see, you didn't include the code for that in your question.
If you want to use css_files() or similar, you need to use self.render_string() in order to give Tornado a chance to insert the CSS tags in the proper places.
For an example of how to use tornado.web.UIModule, see this Slideshare presentation
I am going through a short Python tutorial, but I can't get the last exercise to work.
This is the source code of app.py
import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
greeting = "Hello World"
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()
and this is the view, index.html
$def with (greeting)
<html>
<head>
<title>Gothons of Planet Percal #25</title>
</head>
<body>
$if greeting:
I just wanted to say <em style="color: green; font-size: 2em;">
greeting</em>.
$else:
<em>Hello</em>, world!
</body>
</html>
The file app.py is under this directory: C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin
and index.html is at: C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\templates
So, when I want to run the sample code, I type this in the command prompt:
C:\Python26\python.exe "C:\Users\Lucas\Desktop\Learn Python The Hard Way\ex50\gothonweb\bin\app.py"
After that, "http://0.0.0:8080" is displayed on the console, so I go to http://localhost:8080/ in my browser
but I get back a long traceback starting with
<type 'exceptions.AttributeError'> at /
No template named index
Python C:\Python26\lib\site-packages\web\template.py in _load_template, line 992
Web GET http://localhost:8080/
What is going on and how do I fix it?
Thanks in advance!
I had this problem as well but running on OSX. Ultimately Zed Shaw saw my pleas for help and saw the mistake I was making.
I was running
~/projects/gothonweb/bin $ python app.py
Zed reminded me that I needed to be running this:
~/projects/gothonweb $ python bin/app.py
to allow the templates folder to be found. After I did that it worked like a charm.
in windows ,the folder'name must write like this "c:\" not "c/",and you must use full path.
so the right code is render = web.template.render('d:\\documents\\python\\templates\\')
(app.py is in d:\documents\python)
You have a few typos, you need to refer to your view as Index when you use render (needs to be the same as the class name for your route):
return render.Index(greeting = greeting)
And your urls tuple needs a trailing comma:
urls = (
'/', 'Index',
)
Also make sure your template is named Index.html. Although, looking at the web.py tutorial, it looks like by convention you'd use lowercase for your route class.
Well, I suffered from the same problem, and I must say the error message is right, which indicates "you" cannot find the file, simply because you are not in the right path. So #davidheller #shellfly are right.
I use PyCharm as IDE to write python, so here is my solution:
Since I run the app.py, which is under the bin directory, thus render = web.template.render('../templates/')
which .. goes up and then found the file.
To conclude, we must be sure about the current path(even in windows), and both relative path or absolute path can be used in Windows environment, as shown below:
Absolute path.
Absolute path. Since Windows accepts both "/" and "\", we can write
render = web.template.render('C:/Users/Lucas/Desktop/Learn Python The Hard Way/ex50/gothonweb/templates/')
or
render = web.template.render('C:\\Users\\Lucas\\Desktop\\Learn Python The Hard Way\\ex50\\gothonweb\\templates\\')
Note, python interpreter interprets "\\" as "\"
Relative path.
render = web.template.render('../templates/')
You may need to compile the template like so
python web/template.py --compile templates
anyone using web.py with the Google app engine you will need to.
I am doing the same exercise and I simply go on cmd , cd to my lpthw directory which contains the folders of the project skeleton inside and do:
> python bin/app.py
I think you have to put all your files from the project skeleton in one folder and run your app from there. Hope this helps. :)
Currently, I'm using request.params["filename"] to access uploaded files.
In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]?
Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, you could search through the params or request.POST looking for values of the type cgi.FieldStorage
It's not the file name that's used as a key in request.params, it's the field name that was used in the HTML: <input type="file" name="fieldname">