質問

So I'm fairly new to Django and am creating some simple websites. Right now I am trying to create a website that can be used to host some of my other apps. At the moment, the main site renders the navbar by passing a dictionary of names/urls to a template. For example, this is the main website's views.py:

from django.shortcuts import render_to_response

navbar = [{'Home': '/'},
          {'Apps': '/apps/'},
          {'Dropdown': '',
          'Google': 'http://www.google.com',
          'Stackoverflow': 'http://www.stackoverflow.com'}]

context = {'navbar': navbar}


def home(request):
    return render_to_response("website/home.html", context)


def apps(request):
    return render_to_response("website/applist.html", context)

What this results in is both the home view and the app list view have a nav bar containing a link to website.com/, website.com/apps/, and a dropdown with the title "Dropdown" containing links to google and stackoverflow.

My issue is that I have created another app with its own views that render to other templates using its own context values. So for example, it may use:

def appview(request):
    ## view logic...
    context = {"users": users, "comments": comments}
    render_to_response("app/response.html", context)

If I wanted to, I could switch up the app to take an argument that would replace "app/response.html" with "website/apprender.html", i.e.:

def appview(request, template):
    ## view logic...
    context = {"users": users, "comments": comments}
    render_to_response(template, context)

but the context would still only contain users and comments, and not my navbar info. I am thinking that I should add another argument for an input context that the app would just add to, i.e.

def appview(request, template, context):
    ## view logic...
    context["users"] = users
    context["comments"] = comments
    render_to_response(template, context)

but I want to know what the best practice is. So what is the best practice?

役に立ちましたか?

解決

Best practice for handling anything is debatable. When creating a navbar I would suggest one of the following:

  • Implement the navbar as a templatetag. The templatetags can be loaded in any template and produce a consistent navbar across the project, or just be included in the base.html. If you wanted to hook into this navbar, you could do that by allowing the templatetag to tag a parameter which would be a list of additional menues, or delta values for the existing menu structure.

  • Another solution if your navbar should never change is to code it in directly in your base.html file, which other templates would inherit from. Changing the navbar would require a new commit to your project in any case, and you could avoid complicated template logic to produce the html for it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top