1

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

1
  • bro u just return a dict instead of 2 string in get_title_and_text(). this will solve your issue Commented Oct 7, 2021 at 8:41

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.