skip to Main Content

I have home.html in my Django app, with the table in which if display all my posts:

{% for post in posts %}
                <tr>
                    <td>{% pagination_reverse_numbering paginator page_obj forloop.counter0 %}</td>
                    <td style="width:10%"><a class="mr-2" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></td>
                    <td><a class="mr-2" href="{% url 'user-posts' post.author.id %}">{{ post.author.first_name }} {{ post.author.last_name }}</a></td>
                    <td>{{ post.date_posted|date:"j.n.Y" }}</td>
                </tr>
            {% endfor %}

Problem is, sometimes a single text, like post name is large and then each post is multiple rows. I would like to keep the size of each cell, just when text for preview would be larger then original/default cell size in table, just to skip rest of text. For example, instead of ‘Very long long post title’ it should be ‘Very lon…..’ to preserve cell size.

I would like to implement this in html or js.

I tried:

<td style="width:10%">

but this only limits cell width, then text splits in multiple rows.

2

Answers


  1. As @iklinac link suggestes, you can use the Django built in template filter

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatechars

    You can set a title attribute on the html element to display the whole text on hover.

    Login or Signup to reply.
  2. You can use CSS to limit the text length and show ellipsis when the text exceeds the cell size.

    <td style="width:100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
        <a class="mr-2" href="{% url 'post-detail' post.id %}">{{ post.title }}</a>
    </td>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search