Best way to override per-page templates without clobbering user changes?

32 views
Skip to first unread message

Eric Holscher

unread,
Mar 13, 2015, 7:09:04 PM3/13/15
to sphin...@googlegroups.com
Hi,

I am looking for the best way to include a bit of code in the <head> of each page that Sphinx renders. Historically we've done this by overriding the layout.html, but then this means that a user can't then later also override the layout.html in their own code. I have looked at a few ways of doing this, but none seem quite "right":

Add to metatags
----------------------

This is the way that the google analytics sphinx-contrib app works. It appends something to the ``metatags`` variable in the template context:


This works, but it also appears at the top of the <head>, and feels pretty hacky. It also doesn't work if you want to include a set of javascript at the bottom of the <head>, after other javascript files have been run.

This also depends on themes having this block in them, which isn't always the case.

Add a custom node
--------------------------

I've also looked at adding a custom node to the doctree. This works great, but I couldn't figure out how to make the custom node be rendered into the <head> of the document instead of the body. In docutils I can set self.head on the writer, but it seems Sphinx doesn't use this, and only renders the body from the doctree.

Hooking into html-page-context
-----------------------------------------

I could override the page.html template and add things there, but again this would break that functionality for users.


Conclusion
---------------

There is no standard way in Sphinx to actually add a bit of HTML to the <head> of the document in a way that will work across themes and not inhibit other uses of said functionality. Does anyone else have an idea for how to do this in a sane way?

Takayuki Shimizukawa

unread,
Mar 14, 2015, 9:39:11 AM3/14/15
to sphin...@googlegroups.com
Hi Eric,

As you mentioned, there is no standard way in 1.3 version.
I don't think it's a good idea to bring a js tag to reST files.

This is just a idea, html_javascripts (setting in conf.py) feature can provides such behavior without writing html depended notation for each reST files, as like as the html_sidebars setting,

--
Takayuki SHIMIZUKAWA

Eric Holscher

unread,
Mar 17, 2015, 8:42:53 PM3/17/15
to sphin...@googlegroups.com
Hmm that seems okay. Then it's just iterated over in the templates in the <head>? 

My main worry with that is depending on templates to actually have the correct logic. I wish there was something similar to the doctree, but for <head>, so that I could programmatically manipulate it in Python, instead of trying to do it in HTML/Jinja. That makes it way less brittle, and able to be done deterministically on build no matter what templates are being used.
Reply all
Reply to author
Forward
0 new messages