I'm need to use multiple return values from a function in HTML
Thats short version of the code. All imports are correct and if I return single value it works. Just don't know how to call both values in the HTML.
In the view:
def get_title_and_text():
title = 'Some title'
text = 'Some text'
return title, text
def page():
return render(request, 'page.html', {'get_title_and_text': get_title_and_text()}
In the HTML
<h3>{{ get_title_and_text.title }}</h3>
<h3>{{ get_title_and_text.text }}</h3>
I guess it's simple solution but I just could not find information about that matter
CodePudding user response:
In the view:
def get_title_and_text():
title = 'Some title'
text = 'Some text'
context = {
'title' : title,
'text' : text
return context
def page():
return render(request, 'page.html', context)
in html
<h3>{{ title }}</h3>
<h3>{{ text }}</h3>
CodePudding user response:
There are two options: working with a subdictionary, or working with indices:
Option 1: subdictionaries
def get_title_and_text():
title = 'Some title'
text = 'Some text'
return {'title': title, 'text': text }
Option 2: construct the context in the function
Another option is to construct the entire context in the function, in that case we work with:
def get_title_and_text():
title = 'Some title'
text = 'Some text'
return {'title': title, 'text': text }
and call the function with:
def page():
return render(request, 'page.html', get_title_and_text()}
in that case you can render the page with:
<h3>{{ title }}</h3>
<h3>{{ text }}</h3>
Option 3: working with indices
What you basically do is associating a 2-tuple with the get_title_and_text
variable. You thus can access this with:
<h3>{{ get_title_and_text.0 }}</h3>
<h3>{{ get_title_and_text.1 }}</h3>