I need some complicated operations to render some dynamic trees in my front-end. But as I can't find any way to run recursion in my jinja or front-end, I take an approach to make a string in my views.py along with HTML syntax and render them in the front-end to get the desired output something like this (As an example, here I skip the original complicated string because there is no need for it):
in views.py:
test = "<h2>Hi This is from django</h2><ol><li>abc</li><li>mno</li><li>xyz</li></ol>"
mydict={
'test' : test,
}
return render(request, 'app\index.html', mydict)
In index.html:
<div class="container-fluid">
{{ test }}
</div>
My desired output with this code is:
Hi This is from
djangoabcmnoxyz
But the obtain output is:
<h2>Hi This is from django</h2><ol><li>abc</li><li>mno</li><li>xyz</li></ol>
Please suggest to me, is there any way to render the jinja string variable along with the effect of HTML in my front-end? If not then how can I take an approach to render any tree dynamically in my front-end where the level, leaf node, intermediate node, etc all info come from the database.
You can use the django-template-filter safe for this.
{{ test | safe }}
Related
I have the following snippet of HTML:
On my django webpage, i get a list that looks as follows:
Each "Part" anchor corresponds with a Part object in Python. Now, I'd like to make it so that when the user clicks on "Part_2", the datapoints of that Part are shown just below it.
On the image, the datapoints of the first part are shown within the nested list. I hard coded this. I looked into calling a python function with an argument from the template, but that is not possible.
What would be an easy way to make this happen?
You can achieve this on the client side. First, create a detail element in your HTML and put a summary and the tags that you need (in this case, I'll be using a <p></p>) as childs:
<details>
<summary>Part 1</summary>
<p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>
What's inside the summary tag will represents the title and below that goes the hidden text that can be accessed by clicking in the arrow on the side of the title.
Then, make sure you filter in your function in views.py the parts by part_1 and part_2 and then pass them into your context. Lastly, render the items like this:
<details>
<summary>Part 1</summary>
{% for part in part_1 %}
<p> {{ part.tag }}</p>
{% endfor %}
</details>
I am creating a web store with HTML and Bottle (Python). I know how to pass data between HTML and Python, as well as how to write Python code inside HTML (reference: http://karrigell.sourceforge.net/en/pythoninsidehtml.html).
What I struggle with is writing Python code inside the reference that gets passed from HTML to Python.
I load images from a database since I have a lot of them. I set and pass the variables image_name(index) to HTML like this:
#get('/store')
def showStore():
images = models.images() # reads from database
data = ', number_of_images={}'.format(len(images))
for (id, title, path) in images:
data += ', image_name{}={}, '.format(id, path)
data += 'image_title{}={}'.format(id, title)
return template('store.html' + data)
The relevant part of store.html:
<!-- Portfolio Gallery Grid -->
<div class="row">
<% for i in range(1, number_of_images+1): %>
<div class="column">
<div class="content">
<img src="static/images/{{image_name<%i%>}}.jpg">
<h3> {{image_title<%i%>}} </h3>
</div>
</div>
<% end %>
</div>
Since Bottle is not that well known: {{image_title}} in HTML gets the value passed in from the template (html, variables). Block <% %> enables you to write Python code inside it.
Everything worked properly when I didn't use indexing of image properties inside the HTML, so HTML and the for loop do work, the problem is with this part:
{{image_title<%i%>}}
<%i%> should in my opinion create a variable image_titlei but apparently it doesn't.
I get a template not found error, probably because the variables I am passing in (from the .py file) do not exist in the HTML.
The reason I would very much like to do this dynamically instead of hardcoding every image is that I have a lot of those images and every image has a whole table of relevant data I left out here because I would retrieve it in the same way as image's name and title.
I would appreciate any help with proper combining Python inside HTML with variables passed in since I really want to do it dynamically
There are a rather large number of things wrong here.
Your template not found error is actually nothing to do with the strange manipulations you are doing within that template. It is because you are concatenating the template name with the data string in your call to template() in the last line of your Python code. I don't know bottle, but I'm absolutely positive the data needs to be a second parameter to that function:
return template('store.html', data)
As for the rest, there's absolutely no need to do anything that you are doing there. Just pass the images as a list, and iterate through that list in the templates. Dynamic variables are always a bad idea, and that applies just as much to templates as it does to standard Python code.
(Although note that you don't even create any dynamic variables; you just have a single string, formatted to look like a set of variable assignments. But that doesn't make it actually assign any variables anywhere.)
I would like to use Django build-in tools to print breadcrumb string in the html-template file, for example like this:
domain_name/accounts/14
Where each part between / will lead to its corresponding page. Is it achievable using {{ request.path }} and https://docs.djangoproject.com/en/1.9/ref/templates/builtins/ ?
The tasks I see:
Remove first slash '/' from the `{{ request.path }}'
Break {{ request.path}} value into pieces (divided by '/')
Apply link to each piece
I don't think the string manipulation you want to do is possible from the template side. I think a possible way is using a custom template filter that receives request.path and returns a list of tuples (link, text) and then iterate over that list on the template side and create the breadcrumbs.
https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#writing-custom-template-filters
In my django app's index.html (which I consider as the home page of the site)I am giving links to various locations in the website.When the user reaches one of the locations,he should find a link there, to get back to the home page.So I created a base.html to be inherited by all the pages including index.html.In the base.html,I am providing these links.
base.html
...
Archives
<br/>
Reports
<br/>
Home
<br/>
..
My problem is that ,when I am on index page(home) ,I don't want to display the home link.Is this possible to do so in the template,using an {% if %} condition?
Currently I am not passing any parameter in the view
#login_required
def index(request, template_name):
print 'index()::template=',template_name
return custom_render(request, {},template_name )
def custom_render(request,context,template):
req_context=RequestContext(request,context)
return render_to_response(template,req_context)
Firstly, you can use the django render shortcut to avoid having to use the long-winded custom_render.
from django.shortcuts import render
#login_required
def index(request, template_name):
return render(request, template_name,extra={})
You can be cheeky and in your base.html do something like:
{% url home as home_url %}
{% if request.path != home_url %}Home{% endif %}
to quickly check if the current page is the home page.
If it might get more complicated in the future, you can use a template tag to check whether or not the current URL you are on matches another URL. Here is a template tag I have used before to check if a menu link is currently active:
https://gist.github.com/2049936
This isn't exactly what you asked for, but an alteratively way to do this which I often much prefer is to use JavaScript to either hide or change the color of links to the current page. For example, if you were using jQuery:
// Assumes relative paths in a elements
$('a[href="' + window.location.pathname + '"]').each(function (index, element) {
$(element).addClass('someClass');
});
someClass could be a CSS rule to set the 'display' attribute of that element to 'none', or to simply make the link look like plain text, and behave like plain text when mousing over or clicking on it.
This has two possible advantages:
it prevents your template from becoming too convoluted, and from being difficult to maintain if you start arbitrarily adding nav elements
you have the ability to keep your nav consistent between pages, which in my opinion is a good design decision
It's no silver bullet, but I think it's important to recognise that sometimes these things aren't necessarily best done in templates. I think of my django templates first and foremost as a way of structuring data. There will always be some element of presentation in them, but I try to remove that as much as possible. Others will disagree.
I am using Markdown in an app to display a user biography. I want the user to be able to slightly format the biography, so I'm letting them use the TinyMCE editor.
Then, displaying it in the Django Template like this
{% load markup %}
<div id="biography">
{{ biography|markdown }}
</div>
The problem is, if there is a tag in the biography, it is not being escaped as django does everywhere else. This is the source output from a biography test:
<p><strong>asdfsdafsadf</strong></p>
<p><strong>sd<em>fdfdsfsd</em></strong><em>sdfsdfsdfdsf</em>sdfsdfsdf</p>
<p><strong>sdafasdfasdf</strong></p>
<script>document.location='http://test.com'</script>
How do I set Markdown to escape these malicious scripts?
According to django.contrib.markup.templatetags.markup.markdown's docstrings:
To enable safe mode, which strips raw HTML and only returns HTML
generated by actual Markdown syntax, pass "safe" as the first
extension in the list.
This should work:
{{ biography|markdown:"safe" }}
Markdown in safe mode would remove all html tags, which means your users cannot input HTML segments in the biography. In some cases, this is not preferable. I would recommend you use force_escape before markdown, so anything fed into markdown is safe.
For example, if your biography is <html>I'm really a HTML fan!</html>, using
{{ biography|markdown:"safe"}}
would produce HTML REMOVED.. Instead, if you use
{{ biography|force_escape|markdown }}
The output would be something like
<p><html>I'm really a HTML fan!</html></p>