Django + jQuery: Sometimes AJAX, but always DRY?
Let's say I have an app (in Django) for which I want to sometimes (but not always) load content via ajax.
An easy example is logging in. When the user logs in, I don't want to refresh the page, just change things around.
Yet, if they are already logged in, and then arrive at (or refresh) the same page, I want it to show t开发者_开发问答he same content.
So, in the first case, obviously I do some sort of ajax login and load changes to the page accordingly. Easy enough.
But what about in the second case? Do I go back through and add {% if user.authenticated %} all over the place? This seems cold, dark, and WET.
On the other hand, I can just wrap all the ajaxy stuff in a javascript function, called loggedIn(), and run that if the user is authenticated. But then I'm faced with two http requests instead of one. Also undesirable.
So what's the standard solution here?
I'd go with your second option. Yes, it's some overhead with the two HTTP requests, but since both will be retrieving parts of your page, it's not like you'll be loading the same data twice. It won't be much different from having an image file or javascript library referenced in the page (they also load as separate requests).
Unless you have different sets of information for logged-in and anonymous users, and you don't want to load the anon info and then replace it with the logged-in one. In that case, load shared elements in the main page load, and always load variable parts via Ajax (different data depending on anonymous or logged in user).
Here is a different approach from my other answer. If you don't like the if conditions in templates, I'd recommend using template inheritance. You can use e.g. a two-template approach, and you render one or another in your view based on user.is_authenticated
:
Have a base template with the page for the unauthenticated user (e.g. main_unauthenticated.html). Put all variable parts into blocks:
{% block userinfo %}You are not logged in yet{% endblock %}
Make a main_authenticated.html template that inherits from that one:
{% extends "main_unauthenticated.html" %}
And provide the variable blocks:
{% block userinfo %}Welcome {{ request.user }}{% endblock %}
As a general case template inheritance is more powerful than inclusion.
If they are not significantly different I would use option 1, if there were significant differences I think I would find it easier to maintain two templates for the two different conditions. You could alway use includes if large chunks were the same.
精彩评论