Adding JS To all Opa Resources: Use Case Google Analytics
I decided I wanted to add Google Analytics to OpaDo but had no idea how to easily tell each page to include the necessary Javascript. I asked on the Opa mailing list and got a quick and simple response. Frederic Ye pointed me to Resource.register_external_js
It couldn’t have been any easier. You simply place your google_analytics.js file in your project and use the Resource.register_external_js function to modify the default customization of all Resources. See code below or on the github repo.
package opado.main import opado.user import opado.admin import opado.todo urls : Parser.general_parser(http_request -> resource) = parser | {Rule.debug_parse_string(s -> Log.notice("URL",s))} Rule.fail -> error("") | "/todos" result={Todo.resource} -> result | "/user" result={User.resource} -> result | "/login" result={User.resource} -> result | "/admin" result={Admin.resource} -> result | (.*) result={Todo.resource} -> result do Resource.register_external_js("/resources/js/google_analytics.js") server = Server.of_bundle([@static_resource_directory("resources")]) server = Server.make(urls)
For a longer article/tutorial on dealing with external resources check out this blog post from the Opa team Dealing with External Resources.
Leave a Comment
