Yannick
Yannick

Reputation: 3663

Want to display the first character of lastname in django templates

I want to display the first character of lastname in lowercase in django templates.

For example:

name = "Yannick Morin"

Result should be "m"

I've written the following code:

{{ name|first|lower }}

But it will return the first letter "y" and not the one from the last name.

Thanks for any help.

Upvotes: 3

Views: 1210

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47846

You can write a custom template filter for it.

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

In the template, you can use it like:

{{ name|last_name_initial }}

Upvotes: 3

Related Questions