Silver Light
Silver Light

Reputation: 45932

Django: Get custom tag output inside a view

I have a very specific problem.

I wrote a special template tag to display some peace of HTML code based on some calculations. Tag call looks like this:

{% chord 'A' %}

And the output generated is

<div class="chord">A <audio src="/media/chords/A/A.mp3" controls>Not supported</audio></div> 

Everything works fine, but I came to stage where I need to put this output inside a variable in my view, not in a template. Is it somehow possible? Is there a method, that I can call from inside a view, to get custom tag output with a given parameter?

Upvotes: 1

Views: 219

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

Well, you could just define a template string inside your view and render it:

tpl = Template("{% load chord %}{% chord 'A' %}")
html = tpl.render(Context())

but a better approach might simply be to extract the logic for the tag code into a utility function that you can call both from your view and from the template tag itself.

Upvotes: 3

Related Questions