rust-lang / mdBook

Create book from markdown files. Like Gitbook but implemented in Rust

Home Page:https://rust-lang.github.io/mdBook/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to update "context" object being passed to index.hbs?

prnvbn opened this issue · comments

In the user guide section 5.3.1 it is mentioned that

A lot of data is exposed to the handlebars template with the "context". In the handlebars template you can access this information by using

{{name_of _property}}

Is there a way to update this "context" object in a preprocessor? I tried updating the context using the following code inspired by implementing a preprocessor with a different language

from distutils.log import debug
import json
import sys

if __name__ == "__main__":
    if len(sys.argv) > 1:  # we check if we received any argument
        if sys.argv[1] == "supports":
            # then we are good to return an exit status code of 0, since the other argument will just be the renderer's name
            sys.exit(0)

    # load both the context and the book representations from stdin
    context, book = json.load(sys.stdin)
    # # and now, we can just modify the content of the first chapter
    # book["sections"][0]["Chapter"]["content"] = "# Hello"

    context["test"] = "HELLO WORLD"
    debug(context)

    # we are done with the book's modification, we can just print it to stdout,
    print(json.dumps(book))

In the index.hbs, I try to access it like so:

            <div>
                {{ test}}
            </div>

The PreprocessorContext is read-only in a preprocessor. The context mentioned in the handlebars template is something different, and is only created just before rendering the HTML. For the most part, preprocessors are intended to be renderer-independent.

Is there a way to update the context that is passed to handlebars? I am trying to dynamically pass some information to the index.hbs file and was hoping I could do so using the context object

I don't think so. I think I'm not understanding why you would want to pass {{foo}} instead of just inserting the content you want directly.

I do not want to insert it in content. I want to add {{foo}} in the sidebar or somewhere else that is outside of content is currently only accessible via mdBook