jayt
jayt

Reputation: 768

Django - Reducing duplicate context code in the view

Say I have a view function like so:

def check_view(request):
    if user.is_authenticated:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variablec':c}
    else:
        ...
        return render(request, 'user-template.html', {'variablea':a, 'variableb':b, 'variabled':d}

Is there any way to only write the context variables just one time (given that there some similar variables for both conditions), but the variables that are different can be written under their own parent conditions?

So variable C will belong to the if statement and D to the else, whereas both variables A and B can be written once but apply to both the if and else statement....

Note how the last variable for each condition is different (c and d)

Thanks

Upvotes: 2

Views: 146

Answers (2)

nimasmi
nimasmi

Reputation: 4138

Yes. Define the variables dict once, and then update it in a single if-block if you need to.

def check_view(request):
    variables = {'variablea': a, 'variableb': b, 'variablec': d}
    if user.is_authenticated:
        variables['variablec'] = c
    return render(request, 'user-template.html', variables)

Upvotes: 1

Withnail
Withnail

Reputation: 3178

It's just a dictionary, so set the ones that are consistent across all of the conditions, and then add the other one in in your if/else logic.

def check_view(request):
    context = {'variablea':a, 'variableb':b}
    if user.is_authenticated:
        context['variablec'] = c 
    else: 
        context['variabled'] = d

    return render(request, 'user-template.html', context) 

Upvotes: 3

Related Questions