Skip to content

How To insert extra tags into head block in base.html (mkdocs)

Summary

This is a short post to describe how to insert extra tags in to <head> block in your doc or blog site built by mkdocs.

At the end you will see how I added adsense to my mkdocs site.

This post is going to follow the recommanded approach. For more detail see Overriding blocks.

Create overrides dir and main.html file

If this is not created, please create overrides dir. Then create main.html under it.

mkdir overrides
touch overrides/main.html

Note

This need to be created directly under your project dir.

.
|-- docs
|   |-- index.md
|   |-- posts
|   |   `-- ...
|-- mkdocs.yml
|-- overrides
|   `-- main.html
`-- requirements.txt

Adding Overrides to mkdocs.yml

If this is not done, add below under theme to mkdocs.yml file in your project

custom_dir: overrides

Example

Below is how my mkdocs.yml looks like:

site_name: Nap Tech
site_url: https://xinap.github.io
theme:
    name: material
    custom_dir: overrides

Adding content to main.html

Add below to html to insert additional tags into <head>

{% extends "base.html" %}

{% block extrahead %}
  <script>...</script>
{% endblock %}

Example

Replace <script>...</script> with your code. Below is an example of of you can add adsense to your mkdocs site.

{% extends "base.html" %}

{% block extrahead %}
  <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxx"
    crossorigin="anonymous"></script>
{% endblock %}

Reference

Original Solution
Official Doc
Code that the solution replaces


Share on Share on

Comments