Display Text in Template? - python

I have a text field in my model that contains markdown text. I need to convert the text to html and show it in my .pt template. what is the best way to do it?
I realise that I can add a method to my model that converts the field and returns HTML, and then call the method from my template, but can I do it without this extra method, by using only the markdown field in my template similarly to Django's?
{{ mytext|markdown:"safe" }}

Plone, which uses TAL for it's templating engine and can use StructuredText, reStructuredText, and other rich text formats, does all the rendering to HTML outside TAL. So you might be barking up the wrong tree in the approach you're going for.
That said, TAL has a somewhat extensible "expression" system which is why you can have path expressions (the default) or python expressions. In the zope world, which includes plone, there's a page composition system called content providers, so someone implemented a provider tal expression. So maybe you can look at that:
tales.py
configure.zcml
The structure keyword is still your easiest bet.
<div tal:replace="structure view/getMarkdown">rendered markdown</div>
But structure is a special case keyword and not an extensible part of page templates.

Related

How to fill data in a base html file Django

I have a base html file (for which code shouldn't be necessary) that requires some tags in the menu to be filled with id numbers (which are dynamic, and can't be hard coded). It seems to me that writing code to populate the tags for each view violates the DRY principle, and as such there should be some way to provide variables to a base html document. How does one do this, if it's possible?
You have two options:
Custom template tag
Custom context processor
Which way to use depends on your specific needs.
Yes. You need to use Context Processor. Google "django context procoessor" it'll come up with many results.

Django template filters, tags, simple_tags, and inclusion_tags

This is more of a general question about the distinctions between these four different kinds of django tags. I just read the documentation page on template tags:
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
But I'm finding it difficult to know when I should use one variation over another. For example, what can a template tag do that a simple_tag cannot? Is a filter limited to manipulating strings only and is that why the documentation says that template tags are more powerful because they can "do anything"?
Here is my perception of the distinctions:
template filters: only operate on strings and return strings. No access to models?
template tags: access to anything you can access in a view, compiled into nodes with a specified render function (it seems like the only advantage is that you can add variables to the context?)
simple_tags: take strings and template variables and returns a string, you are passed the value of the template variable rather than the variable itself (when would you ever want the variable itself over the value?)
inclusion tags: allow you to render arbitrary extra templates
Can someone give an example outlining when I would want to use one of these over another?
Thanks.
Template filters can operate on any object (and at most two at once). They're just functions that take one or two arguments. e.g.
# filter implementation
#filter
def myfilter(arg1, arg2):
....
# usage in template
{{ arg1|myfilter:arg2 }}
They are limited in that they cannot access the template context, and can only accept a limited number of arguments.
Use case: You want to use modify one of the variables in the context slightly before printing it.
Template tags can change the way the rest of the template is parsed, and have access to anything in the context in which they are used. They're very powerful. For example I wrote a template tag that subclasses {% extends %} and allows a template to extend different templates based on the current User.
You can easily recognise template tags when they are used, because they around surrounded in {% and %}.
Use case: You want to perform some logic that requires Python code and access to the template context.
Inclusion tags are still template tags, but Django provides some helpers (i.e. the #inclusion_tag decorator) to make it easy to write template tags of this kind.
Use case: You want to render one template into another. For example you may have an advertisement on your site that you want to use in different places. It might not be possible to use template inheritance to achieve what you want, so rather than copy/paste the HTML for the ad multiple times, you would write an inclusion tag.
The reason why you would use an inclusion tag over the existing {% include %} template tag, is that you may want to render the template with a different context to the one you are in. Perhaps you need to do some database queries, to select the correct ad to display. This is not possible with {% include %}.
Simple tags like inclusion tags, simple tags are still template tags but they have limited functionality and are written in a simplified manner. They allow you to write a template tag that accepts any number of arguments (e.g. {% mytag "some str" arg2 arg3 %} etc) and require you to only implement a function that can accept these arguments (and optionally a context variable to give you access to the template context.
Essentially they're an upgrade from template filters, because instead of accepting only 1 or 2 arguments, you can accept as many as you like (and you can also access the template context).

How does Django handle escaping when I use a TinyMCE editor?

How do I display only bolds, italics, and all the other non-security issue HTML on the page?
Sanitizing HTML is a pretty hard problem to get right. Spammers and other nasty people come up with new ways to smuggle HTML through sanitation all the time. The safest option is to define a white list of harmless tags and rigorously filter out all other tags with a true HTML parser (not with regular expressions).
There are a couple of template tags and filters on djangosnippets.com, e.g. this or this one. When selecting a filter, pay attention that it uses a white list and an HTML parser like lxml.html (preferably lxml.html.clean) or BeautifulSoup.
Probably it makes more sense to configure TinyMCE that way the user can only enter elements you allow him. TinyMCE has a powerful set of rules for that. If you are using django-tinymce see this for setting TINYMCE_DEFAULT_CONFIG to your desired options.
To display all HTML (no-escaping) you can use safe filter
{{ var|safe }}
In your case, if you want to escape everything except certain tags, you can write you own filter that does that:
{{ var|mysafe }}
Read about it here: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
The algorithm of the filter could be:
Escape everything
Unescape only those tags that are
allowed (by using .replace or
regilar expressions)

How to implement Symfony Partials or Components in Django?

I've been developing in the Symfony framework for quite a time, but now I have to work with Django and I'm having problems with doing something like a "component" or "partial" in Symfony.
That said, here is my goal:
I have a webpage with lots of small widgets, all these need their logic - located in a "views.py" I guess. But, how do I tell Django to call all this logic and render it all as one webpage?
It sounds like what you're looking for is something like custom template tags...
You can write your own set of tags that process custom logic and return template chunks that are reusable in a very widget-like way.
Assuming you are going to be using the components in different places on different pages I would suggest trying {% include "foo.html" %}. One of the (several) downsides of the Django templating language is that there is no concept of macros, so you need to be very consistent in the names of values in the context you pass to your main template so that the included template finds things it's looking for.
Alternatively, in the view you can invoke the template engine for each component and save the result in a value passed in the context. Then in the main template simply use the value in the context.
I'm not fond of either of these approaches. The more complex your template needs become the more you may want to look at Jinja2. (And, no, I don't buy the Django Party Line about 'template designers' -- never saw one in my life.)

Rendering JSON objects using a Django template after an Ajax call

I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is:
formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Django that catches the call and passes it to a view function
in the Python view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or simplejson)
define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.
Now, what I still don't get is how are Django templates related to all of this? Apparently, we're not making use of the power of templates at all.
Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...
The only resource I found that goes in this direction is this snippet (769) but I haven't tried it yet.
Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.
Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?
Many thanks!
UPDATE: please use snippet 942 because it is an enhanced version of the one above! I found that the inheritance support works much better this way..
Hey thanks vikingosegundo!
I like using decorators too :-).
But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:
Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse:
........
<div id="results">
{% block results %}
{% for el in items %}
<li>{{el|capfirst}}</li>
{% endfor %}
{% endblock %}
</div><br />
........
By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this:
from django.template import loader
# downloaded from djangosnippets.com[942]
from my_project.snippets.template import render_block_to_string
def ajax_view(request):
# some random context
context = Context({'items': range(100)})
# passing the template_name + block_name + context
return_str = render_block_to_string('standard/subtemplate.html', 'results', context)
return HttpResponse(return_str)
Here is how I use the same template for traditional rendering and Ajax-response rendering.
Template:
<div id="sortable">
{% include "admin/app/model/subtemplate.html" %}
</div>
Included template (aka: subtemplate):
<div id="results_listing">
{% if results %}
{% for c in results %}
.....
{% endfor %}
{% else %}
The Ajax-view:
#login_required
#render_to('admin/app/model/subtemplate.html')#annoying-decorator
def ajax_view(request):
.....
return {
"results":Model.objects.all(),
}
Of course you can use render_to_response. But I like those annoying decorators :D
There's no reason you can't return a rendered bit of HTML using Ajax, and insert that into the existing page at the point you want. Obviously you can use Django's templates to render this HTML, if you want.
When you are doing Ajax I don't think you have any use for templates.
Template is there so that you can generate dynamic HTML on the server side easily and hence it provides few programming hooks inside HTML.
In case of Ajax you are passing JSON data and you can format it as you want in Python.
and HTML/document elements will be generated on client side using the JSON by some JavaScript library e.g. jQuery on client side.
Maybe if you have a very specific case of replacing some inner HTML from server side HTML then maybe you can use templates but in that case why you would need JSON?
You can just query the HTML page via Ajax and change inner or outer or whatever HTML.
Templates are for the purpose of presentation. Responding with data in format X (JSON, JSONP, XML, YAML, *ml, etc.) is not presentation, so you don't need templates. Just serialize your data into format X and return it in an HttpResponse.
While templates are indeed just for presentation purposes, it shouldn't matter if you are doing it on the serverside or client side. It all comes down to separating the control logic that is performing an action, from the view logic that is just responsible for creating the markup. If your javascript control logic is having to handle how you are rendering or displaying the HTML, then you might be doing it wrong, but if you isolate that rendering logic to another object or function, and just passing it the data necessary for the render, then you should be fine; it mirrors how we separate our controllers, models and views on the server side.
Take a look at the github project: http://github.com/comolongo/Yz-Javascript-Django-Template-Compiler
It compiles django templates into optimized javascript functions that will generate your presentation html with data that you pass it. The compiled functions are in pure javascript, so there are no dependencies on other libraries. Since the templates are compiled instead of being parsed at runtime, the strings and variables are all already placed into javascript strings that just need to be concatenated, so you get a huge speed increase compared to techniques that require you to do dom manipulation or script parsing to get the final presentation. Right now only the basic tags and filters are there, but should be enough for most things, and more tags will be added as people start making requests for them or start contributing to the project.
You can use jquery.load() or similar, generating the HTML on the server and loading it into the DOM with JavaScript. I think someone has called this AJAH.
Unfortunately, Django templates are designed to be executed server side only. There is at least one project to render Django templates using Javascript, but I haven't used it and so I don't know how fast, well supported or up to date it is. Other than this, you have to either use the Django templates on the server or generate dynamic elements on the client without using templates.

Categories