【问题标题】:Want to display the first character of lastname in django templates想在 django 模板中显示姓氏的第一个字符
【发布时间】:2016-04-01 15:02:04
【问题描述】:

我想在 django 模板中以小写形式显示 lastname 的第一个字符。

例如:

name = "Yannick Morin"

结果应该是“m”

我写了以下代码:

{{ name|first|lower }}

但它会返回第一个字母“y”,而不是姓氏中的那个。

感谢您的帮助。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以为其编写自定义模板过滤器。

    from django import template
    
    register = template.Library() 
    
    @register.filter
    def last_name_initial(value):
        """ 
        Returns the first character of lastname in lowercase for a given name
        """
        last_name = value.split()[-1] # get the last name from value
        return lastname[0].lower() # get the first letter of last name in lower case
    

    在模板中,你可以像这样使用它:

    {{ name|last_name_initial }}
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 2016-04-28
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2018-04-30
      • 2013-01-07
      相关资源
      最近更新 更多