0

I have a list of users. And i want to display it in template:

{%- for user in listed_of_users -%}
        <P>{{ user.name  }}</P>
        {%- endfor -%}  

i want to create hyperlink link to user's profile for each user using predefined function "create_link". This function will return the hyper link for each object. So i write a function like below:

def users_list(users):
    return jinja2.Markup('# '.join(map(create_link, users)) )

It will return a list like:

User1# User2# User3# User4#... 

And i have hyperlink under each username.

I display it in template as a string using this syntax:

{{ users_list(listed_of_users)}}

But, I want to display each user like the format above. I tried:

{%- for user in users_list(listed_of_users) -%}
        <P>{{ user  }}</P>
        {%- endfor -%}

However, it does not work. Can someone help me correct it? Thanks a lot!

AgainstPIT
  • 411
  • 4
  • 14
  • With

    {{ user }}

    . It return a string of HTML text. With

    {{ user.name }}

    , it return nothing. So it mean that the users_list function have changed the original list, right?
    – AgainstPIT Aug 10 '12 at 22:21

1 Answers1

0

For one thing, in your example, '# '.join(map(create_link, users)) creates a long string, so you can't iterate over it the way you are trying to do. You could write a lambda expression and do a double map or something, but why not save yourself the trouble and use the create_link function in your template, so if create_link returns valid HTML for a hyperlink, you could shorten what you write to:

{%- for user in listed_of_users -%}
   <p> {{ user | create_link | safe }} </p>
{%- endfor -%}

To set this up, you need to register create_link as a filter called create_link. Since the create_link function only takes in one value, you really only need to add one line of code:

environment.filters["create_link"] = create_link

(where environment is whatever jinja2 environment you are using to render your templates). As a bonus, this means you can also use the filter anywhere. You can find out more on the jinja2 docs on writing custom filters.

Jeff Tratner
  • 16,270
  • 4
  • 47
  • 67
  • Thank you very much jeff. I finally make it using another build-in function i haven't found out at that time. But this filter way is really promising. I will find out more about it. – AgainstPIT Aug 11 '12 at 18:53