0👍
I did changed my templating from django to Jinja2: & with a littel change in my function I was able to render all the images on the template.
JINJA2 Template
Here’s the function:
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))
img_dir = os.path.join(SETTINGS_PATH, "inc/img")
class ImageHandler(webapp2.RequestHandler):
def get(self):
images = os.listdir(img_dir)
template = jinja.get_template('image.html')
template_values = {'images': images}
self.response.write(template.render(template_values))
the HTML:
<ul>
{% for img in images %}
<li><img src="/img/{{ img|e }}"></li>
{% endfor %}
</ul>
I did also get a snippet to render all images in Django but I change my templating system.
If anyone need to get it on Django here’s the snippet:
VIEWS.PY
def index(request):
"""Renders the index for the site."""
images = os.listdir(templates)
images.sort()
for i in xrange(len(images)):
name = name_for_image(images[i])
images[i] = (name, images[i])
return shortcuts.render_to_response('index.html',
{'images': images,},
template.RequestContext(request))
index.html
{% for name, image in images %}
<td>
<a href="{% url caption fn=image %}">
<img src="{% url thumbnail fn=image %}"/><br/>{{ name }}
</a>
</td>
{% if forloop.counter|divisibleby:5 %}</tr><tr>{% endif %}
{% endfor %}
NOTE:The above code for Django needs some tweaking, as it also relies on another function named def name_for_image(image):
which renders names of the images with the img src.
1👍
Your template syntax is wrong.
You can’t use {{ %variable% }}
, it’s either {{ variable }}
or {% function %}
<li><img src="{{settings.img_dir }}{{%object%}}"></li>
should be
<li><img src="{{settings.img_dir }}{{ object }}"></li>
Also your first block that you supplied has multiple errors
{% for object in dd %}
<li><img src="views.img_dir{{% views.img_dir.object.get_absolute_url %}}"></li>
<li><img src="views.img_dir{{% views.img_dir.dd.get_absolute_url %}}"></li>
{% endfor %}
{{% varible %}}
- What is
views.img_dir
? You’ve defined it in your
views.py
I assume, but it never gets passed to the template. Therefor you won’t be able to doviews.img_dir
. (Unless you’ve done some super magic you’re not showing us) - Which leads to
views.img_dir.object
not being able to render. - And lastly,
views.img_dir.object
will never work since (assuming you’ve passed the object to the template) because it’s a string and a string never has the propertyobject
form your for loop.
So as you can see, you have multiple errors in your code and you’ll never get to render the images with that.
- [Answer]-Django Forms: how to re-evaluate default variables for each instance
- [Answer]-Python/Django Memcached keys expiration
- [Answer]-Login_required – login success not redirecting to "next"