Can I suppress newlines after each template tag with Django's template engine?

旧城冷巷雨未停 提交于 2019-12-21 07:34:12

问题


In Rails ERB, you can suppress newlines by adding a trailing hyphen to tags:

<ul>
  <% for @item in @items -%>
    <li><%= @item %></li>
  <% end -%>
</ul>

becomes:

<ul>
    <li>apple</li>
    <li>banana</li>
    <li>cacao</li>
</ul>

Is there a way to do this in Django? (Disclosure: I'm generating a csv file with Django)

Edit: Clarified that the newlines I'm hunting down are the ones left behind after the template tags.


回答1:


The closest I've found to what you're looking for (I'm looking for the same thing) is talk about a future patch, here: http://code.djangoproject.com/ticket/2594.

Unfortunately, it looks like there's not much you can do until they merge that patch in.




回答2:


{% spaceless %}
<ul>
    <li>apple</li>
    <li>banana</li>
    <li>cacao</li>
</ul>
{% endspaceless %}

I am not aware about any way to discard template tags lines. I'd vote for opening bug report.




回答3:


For example:

<ul>
{% for obj in list %}
    <li>{{ obj|linebreaksbr|striptags }}</li>
{% endfor %}
</ul>

Or this, which also strips whitespaces/tabs/etc, between HTML tags:

{{ spaceless }}
<ul>
{% for obj in list %}
    <li>{{ obj }}</li>
{% endfor %}
</ul>
{{ endspaceless }}



回答4:


It is 2016 now, and I think this issue is still present. In this tutorial https://www.youtube.com/watch?v=vQjmz9wCjLA at around 1:45 a unittest of a template shows that there is a trailing newline on the end of the tag.




回答5:


When you write a template, you could open the ul hardcoded in the template and looping trought items en returning there value with the in it.

As far as i know there isn't a default function for that.



来源:https://stackoverflow.com/questions/2606149/can-i-suppress-newlines-after-each-template-tag-with-djangos-template-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!