What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.
So:
Web designers: what templating engine do you prefer to work with?
programmers: what templating engines have you worked with that made working with web designers easy?
I had good votes when answering this same question's duplicate.
My answer was:
Jinja2.
Nice syntax, good customization possibilities.
Integrates well. Can be sandboxed, so you don't have to trust completely your template authors. (Mako can't).
It is also pretty fast, with the bonus of compiling your template to bytecode and cache it, as in the demonstration below:
>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True)
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None
def root(context, environment=environment):
l_data = context.resolve('data')
t_1 = environment.filters['upper']
if 0: yield None
for l_row in l_data:
if 0: yield None
yield unicode(t_1(environment.getattr(l_row, 'name')))
blocks = {}
debug_info = '1=9'
This code has been generated on the fly by Jinja2. Of course the compiler optmizes it further (e.g. removing if 0: yield None)
Django's templating engine is quite decent. It's pretty robust while not stepping on too many toes. If you're working with Python I would recommend it. I don't know how to divorce it from Django, but I doubt it would be very difficult seeing as Django is quite modular.
EDIT: Apparently the mini-guide to using Django's templating engine standalone was sitting in front of me already, thanks insin.
Look at Mako.
Here's how I cope with web designers.
Ask them to mock up the page. In HTML.
Use the HTML as the basis for the template, replacing the mocked-up content with ${...} replacements.
Fold in loops to handle repeats.
The use of if-statements requires negotiation, since the mock-up is one version of the page, and there are usually some explanations for conditional presentation of some material.
I personally found Cheetah templates to be very designer-friendly. What needed some time was the idea of templates subclassing, and this was something hard to get at the beginning. But a designer creates a full template, duplicating his code... Then you can go clean things up a bit.
To add to #Jaime Soriano's comment, Genshi is the template engine used in Trac post- 0.11. It's can be used as a generic templating solution, but has a focus on HTML/XHTML. It has automatic escaping for reducing XSS vulnerabilities.
Mi vote goes to Clearsilver, it is the template engine used in Trac before 0.11, it's also used in pages like Google Groups or Orkut. The main benefits of this template engine is that it's very fast and language-independent.
I've played both roles and at heart I prefer more of a programmer's templating language. However, I freelance for a few graphic designers doing the "heavy lifting" backed and db programming and can tell you that I've had the best luck with XML templating languages (SimpleTAL, Genshi, etc).
When I'm trying to be web designer friendly I look for something that can be loaded into Dreamweaver and see results. This allows me to provide all the hooks in a template and let the designer tweak it without worrying about breaking what I've already written. It allows us to share the code and work better together where we're both comfortable with the format.
If the designer codes without a WYSIWYG editor, I think you're options are less limited and you could go with your own personal favorite.
Related
In php files, this task may be a simple include of another file but I wondered if it was similar practice in Django? like described here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include
Short answer: No, Python doesn't perform that way.
Here's a long one:
A little bit about difference between PHP and Python web development
First of all, include and require are parts of PHP language itself. It means that before processing source code PHP interpreter includes source code from files given as arguments to those functions and then makes interpreting. That's the inheritance of the main purpose of PHP design (HTML, or, generally, text preprocessing).
Web development in Python is a bit different. Language itself was designed as general purpose programming language, so it doesn't assume text-processing by default. Code is just executed. That's why web development is usually done using frameworks (or wsgi modules if you prefer doing everything from scratch.
All that above means that all text manipulations (all output you generate, you generally do manually by creating result text string (or strings list when used with buffering) and giving the output result yourself.
Template languages
That's kinda messy point from which template languages were born, becoming essential part of every (or almost every) web application written in Python (you can assume something simalar to Smarty in PHP world). There are a lot of them: jinja, jinja2, mako, chameleon ... and many others. All of them are different but serve the same purpose (easyfying text generation via providing templates with placeholders for data of basic representation logic).
And here comes the main feature of Python web frameworks: application logic and representation are strictly splitted.
Here we came to the substance of your question:
As all of those template libraries providing text templating facilities are different, there's no common way to make PHP-like includes that we can say they are general for Python. Each of those tools provide different ways and philosophy of handling, in particular, includes, mainly divided into two mainstream ways:
macros- and slots-based (Chameleon)
template inheritance-based (Jinja2, Django template language)
All you need is to take one that best fits your needs (whether you like/unlike their syntax, some of them are faster, some are more readable, and so on..) and work with it combining with other tools that provide logic for your application.
Getting closer: About Django
It's common to use include template tag when you want to include some re-used part of application (e.g. pagination widget), for which you've adapted your view context.
But when you have common header for all pages, or another common part, it's better to use inheritance, that's achieved in two steps:
Basic template is created (containing general header and footer)
Specific templates are created via template inheritance feature, in particular, extends template tag in Django
Python is not PHP!
Django doesn't allow you to write arbitrary scripts(code) in templates. You should do all the computations/business tasks in views.py (controller) and pass results into template. In template usually you iterate over your result set and display data. In django 1.4 a new assignment tag was added , so you can do
{% get_movie_tickets_for_theater movie theater as tickets %}
but your get_movie_tickets_for_theater will be defined in templatetags python file.
The site won't be that complicated and will resemble a modern blog (users, messages, news and other similar features).
Do I need to use a framework for this, and if so, which is best?
Pyramid, Django?
You certainly don't need a webframework to create a simple website. Given that you're new to python and interested in building a python website, I imagine this implies: you're interested in learning python. If you're exclusively interested in learning django-python, there's no reason you can't jump in to django, as Ronak said, of course. He's right. It has a lot of documentation. But it will make for somewhat of an odd intro to python.
If I were in your shoes, I'd either start making some offline programs first, or consider an ultra-lightweight framework. Many would advocate web2py or pyramid for ultralightweight. I might consider going even lighter. Something like Bottle, where you're more or less just pairing functions with urls. This way you can at least do a bit of hacking/trial-and-error, instead of launching right into django.
It's not that django doesn't use python-- it will tell you many times that it is in fact 'just python.' But it's adapted at its core to be used in a large business setting (the chicago something or other online, i think). So it enforces various rules that are helpful in managing many different employees working on a project together. You may or may not wish for this kind of 'help.' It also means the scale of projects is assumed to be large and the time-horizon, limitless. If you want to see how a python dictionary works, you may not want to spend a long time configuring settings and creating the pseudo-static-typing you need for your database, and so on, just to execute your project and see a result.
I realize I will automatically get downvoted for this, but I believe it to be sound advice.
It depends on what kind of website you are planning to come up with. If the website is going to be just a set of static HTML files, then you don't really need a framework. But if your website will have lots of dynamic content that will get updated on regular basis, you should go with some framework. That will make your life maintaining the website much more simpler.
Django is the most popular framework written in Python. It has very good documentation and a strong community base too.
Go with Django - 10,000 Elvis fans can't be wrong.
Or roll your own from scratch. You'll learn a lot, know everything about how you site works, and better appreciate what a framework does for you.
As RonakG first pointed, it all depends on the kind of website you intend to have up and running. Actually, your question is too general for a single, definitive answer. There are more aspects to consider other than just being in python. For example, deadlines. This means considering the learning curve to achieve your results. If you don't have much time, a steep learning curve (time to learn it in order to develop it) is certainly something you will want to avoid. Perhaps you already develop in other languages, and need integration and/or migration support, need scalability, reusability, etc, etc, etc.
Another thing that is not so clear in your question is what you mean by "The site won't be that complicated and will resemble a modern blog (users, messages, news and other similar features)". If it really resembles just a modern blog, with users, messages and news, you could google for CMS (Content Management Systems). There are many options available, that could make you have your site up and running in almost no-time. All you'll have to learn is how to customize whatever it has to as to comply to your needs.
That said, if you prefer python, there are some good CMSs available which you can develop your site fast, like Plone. And if you prefer Django, there's Django CMS and there's the excellent Pinax project, which takes the django code reusability to deliver you sample fully customizable, complete websites.
I'm adding a simple web interface to an already existing piece of software; web.py fits the job just right and that's what I'm using. Now I'm researching what templating engine to use and came down to two alternatives: either using web.py's own Templator or using Jinja2.
I already have both working in the app and I'm writing some very simple templates in both to explore them. I must say I find Templator easier to read, that's probably due to me being a programmer and not a web designer (who would probably find Jinja easier?).
While I'm only generating (non compliant ;) ugly HTML pages now, I'll also use the templating engine to generate emails and good old plain text files.
Both softwares are "fast enough" for any practical purpose, I'd like to ask people who used extensively one or the other or both what are their strengths and weaknesses in the areas of ease of use, code cleanliness, flexibility, and so on.
Taking a quick look at Templator (which I have never used) and comparing it to Jinja2 (which I have used somewhat extensively), I'd say that the two are pretty similar ... but Templator is closer akin to Mako than to Jinja.
Mako and Jinja both support:
Template Inheritance (You can have a layout that all your pages inherit from)
Whitespace control
While Mako and Templator both support:
Embedding "safe" Python in your templates.
All three support:
Adding to the template context (functions, objects, variables, the works)
Defining functions to encapsulate re-usable pieces of functionality in your templates (Jinja calls them "macros".)
Conditionals and loops
Setting and getting local variables.
Expression evaluation
Caching the compiled bytecode to speed up future execution.
Templator supports on weird thing that I don't believe either Jinja or Mako does:
Setting attributes on the compiled template object from within the template code. (Speaking frankly, actually making use of that feature seems like the wrong thing to do. Any flags that your template could determine need to be set from what has been passed in by the context should already be set by your application code.)
Jinja takes the template code and compiles them to Python bytecode, but it does that for everything, rather than passing through strings to the Python interpreter to use safe_eval. By doing so Jinja2 is theoretically immune to certain types of attacks on the template level (But when you have hostile input from your templates you generally have a much bigger problem).
As for the rest of it, it's all pretty much up to your preference for syntax.
What was hard for me in Templetor is template inheritance. Instead of simple concept of blocks which is present e.g. in Jinja2, you have to select the base template once in the app code, then do the weird attribute setting in the actual template while accessing it in the base template. Still you have problems if you need more than one “big” block like the page body.
Real blocks are much more elegant, and the flexibility of Templetor's “real” Python is not really necessary, while it probably can be unsafe.
I'm creating an app that allows users to query, manipulate, and explore a very large graph.
What's the 'best' way to create a gui + visualization for my project?
By best I mean the following:
1. conforms to web standards, no flavor of the month solution
2. allows creative flexibility
3. intuitive, won't require weeks to learn and months to master
Should I start diving into Django and learning how its MVC works? Everything I've read pisses on Django, but seems like the most used option for GAE.
I'm sorry if this isn't coherent. These technologies are out of my comfort zone, so I have trouble searching for solutions and phrasing my questions.
App Engine is flexible on the UI side. The Python supports Django templates (0.96 out of the box, and 1.2 with a one-line config change). Django templates are easy to use, and are JavaScript toolkit neutral. I use jQuery, but that's a personal choice that App Engine doesn't impose. On the UI side, it's a safe choice, and any time you put in to learning the Django template language and jQuery is portable beyond App Engine. I don't see a lot of pissing on Django, but maybe I'm hanging out in different places.
Though you emphasize the UI side, I'd look first at how to map your large graph on to the App Engine datastore, and how the queries against your graph will perform. The nuances of the App Engine datastore often trip up people who have a lot of relational experience and expect tables and real foreign keys. It's well-suited for storing graphs, but it's worth exploring and prototyping your queries, so that you know what you're getting in to.
The App Engine SDK is great for local (e.g., laptop in a coffee shop) development.
I'm a bit biased, though.
Does it have to be in python? The GAE has wonderful support for GWT. The GWT eclipse plugin can compile and deploy directly to the GAE with no further modification. The best solution that meets all three of your requirements will be to use GWT + GAE/J.
If you're mainly looking for a charting/graphing solution, there are some good solutions based on Flash *gasp* that are pretty easy to use, such as AnyChart.
As a side note, If you're designing any UI, knowing and understanding the MVC pattern is essential. Most other UI design patterns are a derivative of MVC, so you'll probably be learning MVC regardless of what framework you choose.
Good luck
-tjw
With your third requirement in mind: take a look at something like this Protovis interactive graph visualization, or this Infovis graph example (code). I don't know the scope of your task but if you're lucky you might not need to go too deep into the MVC weeds. Taking the second example, the role of the web backend is just 1) to provide some json object with the info you need to lay out, and 2) process responses. (BTW all these links are open source and well documented.) More concretely, say you have a graph with an interface like this: http://thejit.org/static/v20/Jit/Examples/Hypertree/example3.html (formatted source). An outline of how might it look could be as simple as:
Pseudo HTML:
<a_canvas_svg_or_webgl_object id="your_surface"> ... </a_canvas...>
<script src="... // one of the above visualization libraries
<script>
selector(#your_surface...
data = json.gets("/graph/minard/data.json"); //typical method name in these libs
data.do_stuff() // bunch of methods from the visualization guys...
// save state/user input to json object
button.onclick... // do an ajax post to an url like "/graph/a/data.json?extent=1234"
// use something like query string ie, for when 'extent' changes
etc...
Then on the server (example is GAE-compatible microframework Flask pseudocode (but not that pseudo)):
#app.route('/')
def frontpage():
return render_template('your_front_page.html')
#app.route('/graph/<graph_name>/<kind>')
def backend():
if request.method == 'POST':
gql_foo.save_user_stuff(request.json)
if request.method == 'GET':
if kind == 'data.json':
relevant_part_of_graph = request.args['extent']
requested_data = jsonify(db_query(parameters=graph_name...
return requested_data
else:
return 404
If none of this overlaps enough with your application space you will at least get something out of this answer by looking at d3, which is a bit lower level.
I got a project in mind that makes it worth to finally take the plunge into programming.
After reading a lot of stuff, here and elsewhere, I'm set on making Python the one I learn for now, over C# or java. What convinced me the most was actually Paul Graham's excursions on programming languages and Lisp, though Arc is in the experimental stage, which wouldn't help me do this web app right now.
As for web app fast, I've checked out Django, Turbo Gears and Py2Web. In spite of spending a lot of time reading, I still have no clue which one I should use.
1) Django certainly has the nicest online presence, and a nicely done onsite tutorial, they sure know how to show off their thing.
2) Web2Py attracted me with its no-install-needed and the claim of making Django look complicated. But when you dig around on their website, you quickly find content that hasn't been updated in years with broken external links... There's ghosts on that website that make someone not intimately familiar with the project worry if it might be flatlining.
3) Turbo Gears ...I guess its modular too. People who wrote about it loved it... I couldn't find anything specific that might make it special over Django.
I haven't decided on an IDE yet, though I read all the answers to the Intellisense code completion post here. Showing extra code snippets would be cool too for noobs like me, but I suppose I should choose my web frame work first and then pick an editor that will work well with it.
Since probably no framework is hands down the best at everything, I will give some specifics on the app I want to build:
It will use MySQL, it needs register/sign-in, and there will be a load of simple math operations on data from input and SQL queries. I've completed a functional prototype in Excel, so I know exactly what I want to build, which I hope will help me overcome my noobness. I'll be a small app, nothing big.
And I don't want to see any HTML while building it ;-)
PS: thanks to the people running Stackoverflow, found this place just at the right moment too!
You should look at the web2py online documentation (http://web2py.com/book). It comes with a Role Based Access Control (the most general access control mechanism) and it is very granular, you can grant access for specific operation on specific records. It comes with a web based IDE but you can use WingIDE, Eclipse and PyCharm too. It comes with helper system that allows you to generate HTML without using HTML. Here is an example of a complete app that requires users to register/login/post messages:
db.define_table('message',Field('body'),Field('author',db.auth_user))
#auth.requires_login()
def index():
db.message.author.default=auth.user.id
db.message.author.writable=False
return dict(form=crud.create(db.message),
messages=db(db.message.id>0).select())
The web2py project is very active as you can see from the list of changes http://code.google.com/p/web2py/source/list
If you have web2py related questions I strongly suggest you join the web2py mailing list:
http://groups.google.com/group/web2py/topics
We are very active and your questions will be answered very quickly.
I have to say as not particularly skilled developer, the speed at which I have been able to create using web2py has blown my mind. In large part due to the amazing community and the core value Massimo has of making the framework accessible.
When I started I had written 0 lines of code in Python
Never heard of web2py
I've been at it seriously for about a month and have progressed (in my usual fashion) from asking questions that no one could answer (because they didn't make any sense) to coding for hours at a time without picking up a book or asking a question.
I'm really impressed.
I've had positive experiences with Django.
Built-In Authentication and easy to use extensions for registration
Very good documentation
You probable write your HTML templates mostly in base.html, then just use template inheritance (Note: You'll need to write at least a little bit of HTML)
In contrast to Turbogears, Django is more 'out-of-the-box'
I don't have any experience with web2py, but from my impression, it tries to do a little to much 'out-of-the-box'
If you decide to go with Django, make sure that you use its Generic Views. They will save you from writing lots of code, both Python and HTML.
Also, unless there is a very specific reason for you to use MySQL, I advise you to switch to PostgreSQL. Django is much more oriented towards PostgreSQL and it's a much better database anyway.
The online Django documentation is great, this is what put it apart from all the other frameworks. I also recommend the book Practical Django Projects by James Bennett
Django: Heard it has the best administrative
interface. But uses it's own ORM, i.e. doesn't use SQL-Alchemy.
Web2py: Didn't research this.
Turbogears2:
Uses SQL-Alchemy by default, uses Catwalk for admin
interface, but documentation isn't as
great.
I chose Turbogears2 because it uses popular components, so I didn't have to learn anything new...
I've used both web2py and RoR extensively, and while RoR has gotten a lot of popularity and support in the past few years, web2py is simpler, cleaner, less "magical", and yet also offers more (useful) out-of-the-box functionality. I'd say that web2py has more potential than RoR, but it is a relatively new framework and does yet not have the maturity of RoR. (Despite that, though, I'd choose web2py over RoR any day...)
If you "don't want to see any HTML while building it" then you can forget Django. It is not focused on "point-click-done," it is focused on pros going from concept to production in the shortest time possible. The hierarchical nature of the templating language can lead to some very clean overall site layouts. I use Django for all of my larger sites and I love it.
Although it's written in PHP, not Python, you might take a look at the major new version of WordPress that came out about 2 or 3 months ago. In 3.0 they have come a long way from being a "blogs only" environment and there are tons of ready-made templates for it. Of course if you want to tweak a template, well, there's that nasty old HTML again. I am considering using it for my smaller clients that can't deal with the admin of a dedicated server, etc., that tends to come with a Django site.
Update:
Ah, I missed the semi-joke -- I was up too early and that tends to make me tone deaf to humor. As far as using templates from existing sites, I have done this quite successfully with a couple of sites, both those that were static and those originally driven by well-written PHP scripts. I recommend a careful reading of the {% extends %} and {% include %} docs. Both take either a string literal or a variable. I have used the later method and it can be quite useful for a site that has strong hierarchy distinguished by style changes across branches.
It is also worth the time to understand the search order for templates -- it can be used to good effect, but it can be puzzling if you don't grok it. See the template-related items in the settings.py file for this and other useful goodies.