Search code examples
djangotemplateshrefslice

Django add link after slice


i have the following in my html template:

<h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1>
<p>{{ post.content|slice:":1000"|linebreaksbr }}</p>

i want that after the slice to 1000 chars a href to the full article gets displayd. e.g.:

<h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1>
<p>{{ post.content|slice:":1000"|link:"... read on" href= url 'post_detail'|linebreaksbr }}</p>

any idea?


Solution

  • Well separate the text of the partial article from the link. Like:

    <p>{{ post.content|slice:":1000"|linebreaksbr}}
      <a href="{% url 'post_detail' pk=post.pk %}">read on</a></p>

    Typically by splitting up problems in subproblems, the problem becomes easier to manage.

    The {% url ... %} is probably with pk=post.pk or something similar, since otherwise it would link to the post_details, but without a specific post.

    Alternatively, if you only want to show read on when the content is sliced, you can use an {% if ... %}:

    <p>{{ post.content|slice:":1000"|linebreaksbr}}
      {% if post.content|length > 1000 %}
      <a href="{% url 'post_detail' pk=post.pk %}">read on</a>
      {% endif %}</p>