Link JS and CSS files in custom html

What I’m trying to do:
Use JS files and CSS files instead of putting all my JS and CSS in script and style tags in my custom html for a single form.

What I’ve tried and what’s not working:
Honestly not much of anything because I couldn’t find anything in the docs for linking files when the custom html was tied to the form itself rather than a self-standing html file.

I couldn’t find anything obvious in the docs either.

But if you have a CustomHtml form with html like:

<div class="custom-class"></div>
<style>
.custom-class {
    border: 1px solid red;
   height: 30px;
}
</style>
<script>
    function myFunc() {
        return 42;
    }
</script>

And the Form does something like:

class MyForm(MyFormTemplate):
    def __init__(self, **properties):
        self.init_components(**properties)

    def form_show(self, **event_args):
        result = self.call_js("myFunc")
        print(result)

You can move the style to a css file and add the css file to your html like

/* custom.css */
.custom-class {
    border: 1px solid red;
    height: 30px;
}
// custom.js
function myFunc() {
    return 42;
}
<link rel="stylesheet" href="_/theme/custom.css">
<script type="text/javascript" src="_/theme/custom.js"></script>
<div class="custom-class"></div>

More advanced

I might go further and change how I do the JavaScript here
If I create a javascript file that is a module instead I can import the javascript functions into the python directly

My JavaScript file would now look like this

// custom-module.js
export function myFunc() {
    return 42
}

And my python code would look like

from anvil.js import import_from
myFunc = import_from("./_/theme/custom-module.js").myFunc

class MyForm(MyFormTemplate):
    def __init__(self, **properties):
        self.init_components(**properties)
        result = myFunc()
        print(result)


Clone with these examples:

6 Likes

Perfect, that did the trick! Thanks!

1 Like