0

I have Post model for a blog app in Django. It has a field named body. In posts, I may use Latex so I need to use MathJax.js. In some posts, I add code snippet, so I use highlight.js. In some I use both, in some I use none of them.

I want to load the relevant javascript depending on the body field of the Post model (similar to THIS). How can I make the relevant .js file(s) to load automatically?

I know that I can add an indicator field like hasLatex (True, False) or hasCode (True, False). But I'm lazy, I want Post.body to be automatically scanned and only relevant js files loaded.

Community
  • 1
  • 1
HBat
  • 4,873
  • 4
  • 39
  • 56
  • I would just load them both by default, they will get cached by a browser and loaded at most once per user anyway, not much gain in turning them on/off after that. If you still want dynamic js includes - you need to add those boolean latex=yes/no fields, it's a waste to detect latex on every post view rather than during post creation/editing. – serg Apr 01 '17 at 22:57
  • I understand the logic of wasting resources and I agree with the performance gains I would get using a dedicated boolean variable. But still I wonder whether I can do it automatically. – HBat Apr 01 '17 at 23:20

1 Answers1

0

Set something in your context or use a template context processor. For example I load code that handles forms if there is a form key is my context. For something I want on almost every page I put a no_something in my context to disable it. This is done by putting a conditional around the tag in your base template. If the variable is not there or is false it won't show.

What I also do is put my static files in lists inside of my context. JavaScript is in context['js'] and css in context['css']. Those are looped through in my header. I can implement get_context_data in a base class, and all the views that extend from that will have the javascript and css files.

kagronick
  • 2,552
  • 1
  • 24
  • 29
  • I couldn't see how adding `no_something` is different than adding indicator fields in `Post` model. I don't know "template context processor", I'll check that. – HBat Apr 01 '17 at 23:17