Inserting a string function into an HTML document

So I want to be able to insert a function for a string variable which is to be repeated throughout my website.

I have the following function which is located in my __init__.py document

def string(a):
    a = "Hello, this is the repeating string"
    return a

In my HTML document, I have the following to call the function:

<HTML code> {{a}} <HTML code>

Why doesn’t it work? It’s just silly This was how I was taught to call a function, it works in the views module when this is specific to one web page and called via the context variable appended to the ‘render’ function, but when I want this string function to be available to all web pages it just doesn’t want to know. Surely logic would state that this would be the case in the __init__.py document.

It’s just ridiculous.

This isn’t just python. It looks like you’re using a web framework with a templating engine. Can you provide some more details?

I’m using Django

I don’t think the Django templating language lets you execute arbitrary code in your templates–it will call methods of objects but not functions, it seems (I’m not very familiar with Django, I’m just skimming the docs).

Perhaps you need to register your method as a tag to make it available in your templates?

Alternatively it seems you can add variables to all your templates by writing a context processor and adding it to TEMPLATES in your settings.py.

Whatever works :slight_smile:

You, my friend, I want to marry!

Never thought of adding the function to the context_processors in the TEMPLATES section of the settings.py

1 Like