How to pass a variable from Python into Javascript

I’ve tried everything, cannot figure this out!

I’m trying simply to pass a variable in my Python code to the javascript code but when I run the following code I get ‘f-string invalid syntax’ error from Streamlit. The purpose of this snippet of JS is to highlight whatever the variable ‘highlight_content’ is. In this case I just have it set to highlight the word ‘page’. What the heck am I doing wrong here?

        highlight_content = "page"

        # Highlight the source text
        highlight =  f'''

        <script>
        // Specify the section to highlight    
        var section = parent.document.querySelector(".main.css-k1vhr4.egzxvld5");

        if (section) {
        // Specify the keyword you want to highlight
        var keyword = "{highlight_content}";

        // Create a regular expression to match the keyword (case-insensitive)
        var regex = new RegExp(keyword, "gi");

        // Get all text nodes within the section
        var textNodes = parent.document.createTreeWalker(section, NodeFilter.SHOW_TEXT, null, false);
        var node;

        // Iterate through the text nodes and highlight the keyword where found
        while (node = textNodes.nextNode()) {
            if (regex.test(node.nodeValue)) {
            var highlightedText = node.nodeValue.replace(regex, '<span style="background-color: yellow;">$&</span>');
            var wrapper = parent.document.createElement('div');
            wrapper.innerHTML = highlightedText;
            node.parentNode.replaceChild(wrapper, node);
            }
        }
        }
        </script>
            '''
        print(highlight)
        st.components.v1.html(highlight)

Curly braces have a special meaning in f-strings. You need two curly braces to get a single literal curly brace.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.