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.

2
  • 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. Commented Apr 1, 2017 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. Commented Apr 1, 2017 at 23:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.