Django中的前端动态渲染

在和阿里云的合作项目中碰到了一个问题就是,阿里云相关项目的开发后端是Django,话说我一般都是用python写写数据分析脚本或者算法什么的,很少搞后端呢。

我不大喜欢JPA或者thymeleaf之类的,用前后端分离不香吗?

先画个html吧,page_title得加个双花括号:

<!-- Assuming this is in a template called `base.html` that gets inherited by other templates -->
<title>
  page_title
</title>

这里在Django中写一个mixin,这里定义两个功能:类名中的相关类的属性用page_title来定义,另外需要get_title_page的方法来赋值/改变这属性。

class PageTitleMixin(object):
  def get_page_title(self, context):
    return getattr(self, "page_title", "Default Page Title")

  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["page_title"] = self.get_page_title(context)

    return context

实现它:

# Renders "Static Page Title" as the page title
class StaticPageTitleView(PageTitleMixin, View):
  template_name = "index.html"
  page_title = "Static Page Title"

# Renders "Default Page Title" as the page title
class DefaultPageTitleView(PageTitleMixin, View):
  template_name = "index.html"

# Renders "Some Model Attr" as the page title
class DynamicPageTitleView(PageTitleMixin, DetailView)
  template_name = "index.html"
  model = OurModel # assume that it has an attribute called `title`
  context_object_name = "model"

  def get_page_title(self, context):
    return context["model"].title # Assume this returns "Some Model Attr"

当然在原有的mixin部分我们可以做一点微小的工作:

class PageTitleMixin(object):
  def get_page_title(self, context):
    return getattr(self, "page_title", context["user_settings"].site_title)

  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["page_title"] = self.get_page_title(context)

    return context

# We want to inject the `user_settings`object into every single context.
class UserSettingsContextMixin(object):
  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    user = self.request.subdomain_user

    # assume the user has a settings object with a title attribute
    context["user_settings"] = user.settings

    return context

# Use another mixin to encapsulate all mixins for our page.
class PageMixin(PageTitleMixin, UserSettingsContextMixin):
  pass

# Renders "Some User's Title" as the page title
class DefaultPageTitleView(PageMixin, View):
  template_name = "index.html"

知道这是在干什么吗?