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.
In your html template, this:
does not call a function. It is used as the key to the context that is being passed to the render function.
Review the docs at Templates | Django documentation | Django
See the docs for context processors
I also suggest that you spend some more time perusing through the rest of the documentation. Django has a very specific and opinionated way of addressing the fundamentals of a web application. It will benefit you more to start to think about this the way that Django approaches it rather than trying to make it fit your way of thinking.
I do agree with your suggestion, and this is what I’ve been doing. The context sub processor bit I have nailed, just the calling of string variables I don’t.
Thank you x
To rephrase and to try and clarify:
You want to define a function, where the output of that function can be used in a template.
If so, there are two different possibilities - one, the function requires a parameter and, two, the function does not accept parameters.
Since your example shows a parameter (the first case), then what you need to do is pass the output of that function to the context.
e.g.,
context = {
...,
'a': string(a),
...
}
you can then reference that variable as {{ a }}
throughout the template.