python - 模板标签切片不起作用,而 truncatechars 起作用

标签 python django

第一季-办公室。我想删除 -theOffice.因此我做了 season1|truncatechars: "9"但这样就给出了 season 1... 我不想看到... 所以我使用 season1|slice:":9"但这没有任何作用。 这是我的代码。

        <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season|slice:":5" }}

我的完整代码

<div class="row">
  {% for all_episode in episode %}
    <div class="col-6 card" style="padding:20px">
      <a href="{% url 'episode_detail' slug=all_episode.slug %}">
        <img class="card-img-top" src='{{all_episode.image.url}}'>
      </a>
      <div class="card-body">
        <h5 class="card-title">
          <a href="{% url 'episode_detail' slug=all_episode.slug %}">{{ all_episode.title }}</a>
        </h5>
        <p class="card-text">{{ all_episode.story |slice:":100" }}...</p>
      </div>

      <div class="card-footer">
        <small class="text-muted">
          <span class="h5">
            <a href="{% url 'series_detail' slug=all_episode.series.slug %}">{{ all_episode.series }}</a>
          </span> / 
          <span class="h6">
            <a href="{% url 'season_detail' slug=all_episode.season.slug %}">{{ all_episode.season|slice:":9" }}     </a>
          </span>
        </small>
      </div>
    </div>
  {% endfor %}
</div>

最佳答案

这是因为您在模板过滤器中添加了一个空格(或者至少在问题文本中,例如 slice:":9")。

你应该这样写:

{{ all_episode.season|slice:<b>":-9"</b> }}

不是:

{{ all_episode.season|slice:<s>" :-9"</s> }}

-9 表示从字符串末尾算到字符串开头,因此这里我们将省略 9 个字符。 -1 因此会删除最后一个字符。

例如:

>>> Template('{{ s|slice:":-9" }}').render(Context({'s': 'season1-theOffice'}))
'season1-'

关于python - 模板标签切片不起作用,而 truncatechars 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56385600/

相关文章:

python - Django 属性错误 : Form object has no attribute '_errors'

django - 如何使用 django-pytest 跟踪 Django 重定向?

c# - 是否可以在 Iron python 中对带有字符串的动态数组进行排序?

python - 从单个 monorepo 引用多个 Django 项目

python - 查找图像中的所有圆圈

python - 为什么在 python 中使用 dual __init__?

Django - 如何将模型的选择显示为复选框

具有多个 OrderedDictkeys 的 Python xmltodict

python - newArray = myNumpyArray[:, 0] 是什么意思?

python - Virtualenv:全局站点包与虚拟环境中的站点包