开发者

Opinion: Where to put this code in django app:

开发者 https://www.devze.com 2023-01-31 12:58 出处:网络
Trying to figure out the best way to accomplish this. I have inhereted a Django project that is pretty well done.

Trying to figure out the best way to accomplish this. I have inhereted a Django project that is pretty well done.

There are a number of pre coded modules that开发者_如何学Go a user can include in a page's (a page and a module are models in this app) left well in the admin (ie: side links, ads, constant contact).

A new requirement involves inserting a module of internal links in the same well. These links are not associated with a page in the same way the other modules, they are a seperate many to many join - ie one link can be reused in a set across all the pages.

the template pseudo code is:

if page has modules:
 loop through modules:
  write the pre coded content of module

Since the links need to be in the same well as the modules, I have created a "link placeholder module" with a slug of link-placeholder.

The new pseudo code is:

if page has modules:
 loop through modules:
  if module.slug is "link-placeholder":
    loop through page.links and output each
  else:
    write pre-coded module

My question is where is the best place to write this output for the links? As I see it, my options are:

  1. Build the out put in the template (easy, but kind of gets messy - code is nice and neat now)
  2. Build a function in the page model that is called when the "link placeholder is encountered) page.get_internal_link_ouutput. Essentially this would query, build and print internal link module output.
  3. Do the same thing with a custom template tag.

I am leaning towards 2 or 3, but it doesn't seem like the right place to do it. I guess I sometimes get a little confused about the best place to put code in django apps, though I do really like the framework.

Thanks in advance for any advice.


I'd recommend using a custom template tag.

Writing the code directly into the template is not the right place for that much logic, and I don't believe a model should have template-specific methods added to it. Better to have template-specific logic live in template-specific classes and functions (e.g. template tags).

0

精彩评论

暂无评论...
验证码 换一张
取 消