Skip to content

feat: adding custom vars directives #523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changelog.d/523.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
feat: adding custom vars directives
129 changes: 129 additions & 0 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
from datetime import datetime
import os
from pathlib import Path
import sys
from typing import List

from github import Github
import pyvista
import requests
from sphinx.addnodes import document as doctree
from sphinx.application import Sphinx as App
from sphinx.builders.latex import LaTeXBuilder

from ansys_sphinx_theme import (
Expand All @@ -24,6 +27,9 @@
THIS_PATH = Path(__file__).parent.resolve()
EXAMPLE_PATH = (THIS_PATH / "examples" / "sphinx_examples").resolve()

# To allow using 'helper' python file as a module
sys.path.append(str(Path(__file__).parent))

# Project information
project = "ansys_sphinx_theme"
copyright = f"(c) {datetime.now().year} ANSYS, Inc. All rights reserved"
Expand Down Expand Up @@ -265,3 +271,126 @@ def download_and_process_files(example_links: List[str]) -> List[str]:
},
"pdf_guide": {"version": get_version_match(__version__)}, # noqa: E501
}


def remove_edit_this_page_if_directive(
app: App,
pagename: str,
templatename: str,
context: dict,
doctree: doctree,
page_vars: dict,
):
"""Remove 'edit this page' button.

Remove the 'edit this page' link in this page if the page variable
'hide_edit_page_button' is true.

Parameters
----------
app : sphinx.application.Sphinx
Sphinx app
pagename : str
Page name
templatename : str
Template name
context : dict
Page context
doctree : sphinx.addnodes.document
Page doctree
page_vars : dict
Page variables
"""
# Remove the edit button for the index page
if "hide_edit_page_button" in page_vars:
if page_vars["hide_edit_page_button"].lower() == "true":
# breakpoint()
context.pop("theme_use_edit_page_button", False)


def remove_show_source_if_directive(
app: App,
pagename: str,
templatename: str,
context: dict,
doctree: doctree,
page_vars: dict,
):
"""Remove the 'show_source' link.

Remove the 'show_source' link in this page if the page variable
'hide_show_source' is true.

Parameters
----------
app : sphinx.application.Sphinx
Sphinx app
pagename : str
Page name
templatename : str
Template name
context : dict
Page context
doctree : sphinx.addnodes.document
Page doctree
page_vars : dict
Page variables
"""
# Remove the edit button for the index page
if "hide_show_source" in page_vars:
if page_vars["hide_show_source"].lower() == "true":
context["show_source"] = False


def pre_build_page_html(
app: App,
pagename: str,
templatename: str,
context: dict,
doctree: doctree,
):
"""Apply hooks before building HTML.

Apply the hooks as functions before building the HTML files.

Parameters
----------
app : sphinx.application.Sphinx
Sphinx app
pagename : str
Page name
templatename : str
Template name
context : dict
Page context
doctree : sphinx.addnodes.document
Page doctree
"""
from helpers import get_page_vars

page_vars = get_page_vars(app, pagename)

## Hooks
remove_edit_this_page_if_directive(app, pagename, templatename, context, doctree, page_vars)

remove_show_source_if_directive(app, pagename, templatename, context, doctree, page_vars)


def setup(app: App):
"""Add custom configuration to sphinx app.

Parameters
----------
app : sphinx.application.Sphinxlication.sphinx
The Sphinx application.
"""
from helpers import SetPageVariableDirective, add_custom_variables_to_context

# Register the directive
app.add_directive("setpagevar", SetPageVariableDirective)

# Hook into the html-page-context event
app.connect("html-page-context", add_custom_variables_to_context)

# setting pre-build functions
app.connect("html-page-context", pre_build_page_html)
110 changes: 110 additions & 0 deletions doc/source/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""Helper classes and functions for documentation build."""

from docutils.parsers.rst import Directive
from sphinx.addnodes import document as doctree
from sphinx.application import Sphinx as App


def get_page_vars(app: App, pagename: str) -> dict:
"""Get page variables.

Get each page variables.

Parameters
----------
app : app
Sphinx app
pagename : str
Page name

Returns
-------
dict
Dictionary with variables as keys, and their values.
"""
env = app.builder.env

if (
not hasattr(env, "pages_vars")
or not env.pages_vars
or not env.pages_vars.get(pagename, None)
):
return {}

return env.pages_vars[pagename]


class SetPageVariableDirective(Directive):
"""Set page variables.

Set page variables.

Parameters
----------
- variable: str
- value: str

Example

.. setpagevar:: my_key my_value

The key cannot have spaces.

.. setpagevar:: my_key my value

"""

has_content = False
required_arguments = 2 # Variable name and value
optional_arguments = 0

def run(self):
"""Run directive."""
var_name = self.arguments[0]
var_value = self.arguments[1]
env = self.state.document.settings.env

# Store the variable in the environment specific to each page
if not hasattr(env, "pages_vars"):
env.pages_vars = {}

# Store the variable for the current page (env.docname is the document name)
if env.docname not in env.pages_vars:
env.pages_vars[env.docname] = {}

env.pages_vars[env.docname][var_name] = var_value

return []


def add_custom_variables_to_context(
app: App,
pagename: str,
templatename: str,
context: dict,
doctree: doctree,
) -> None:
"""Add customs variables to build context.

This is needed to be able to access the vars at the build stage.

Parameters
----------
app : sphinx.application.Sphinx
Sphinx app.
pagename : str
Page name
templatename : str
Template page
context : dict
Page context
doctree : sphinx.addnodes.document
Page doctree
"""
env = app.builder.env

# Check if there are page-specific variables stored by the directive
if hasattr(env, "pages_vars"):
if pagename in env.pages_vars:
# Add the stored variables to the context for this page
context.update(env.pages_vars[pagename])
5 changes: 5 additions & 0 deletions doc/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ This theme is specifically tailored for documentation related to Ansys projects
helping to ensure consistency in its look and feel. Various useful extensions
are included in the theme to make documentation more appealing and user-friendly.


.. setpagevar:: hide_edit_page_button True

.. setpagevar:: hide_show_source True

.. grid:: 2
:gutter: 2 2 3 4

Expand Down
Loading