Open davep opened 8 months ago
Hi,
It seems that variables are Widget scoped. We can define variables for the whole App. Here is a little dirty hack I wrote to be able to have shared variables for the whole app:
import os
from pathlib import Path
from textual.app import App
from textual.css.parse import substitute_references
from textual.css.tokenize import tokenize, tokenize_values
class MyApp(App):
def get_css_variables(self) -> dict[str, str]:
"""
Dirty hack to add shared variables for the whole app
"""
variables = super().get_css_variables()
last_t = None
current_variable_name = None
css_path = os.path.dirname(os.path.realpath(__file__)) + "/tcss/variables.tcss"
css_content = Path(css_path).read_text()
variable_tokens = tokenize_values(variables)
tokens = iter(substitute_references(tokenize(css_content, (css_path, None)), variable_tokens))
for t in tokens:
if not t:
continue
elif t.name == "variable_name":
current_variable_name = t.value[1:-1]
elif t.name == "variable_value_end":
variables[current_variable_name] = last_t.value
last_t = t
return variables
If it can be usefull for someone...
The documentation for CSS variables doesn't appear to say what the scope of those variables is. For example, it would seem that if you're using
CSS_PATH
, you can't define a series of variables in one file earlier in the path, and then use those variables in files later on in the path. If this is working as intended we should document this.