Home > Software design >  How to call js functions defined in script tag of the erb file?
How to call js functions defined in script tag of the erb file?

Time:05-01

I have a layout for PDF (views/layouts/pdf.html.erb):

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
      function sayHello() {
        return "HAAHAHAhAHAAH"
      }
    </script>
    <style>
    </style>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

I want to use that sayHello() function inside a p tag in app/views/invoices/pdf.html.erb, which gets embedded in yield of layouts/pdf.html.erb

I tried calling sayHello() in different ways like using <%= javascript: sayHello()%> etc.. but nothing works.

I also tried keeping sayHello() in a separate file and then referencing it in javascript_pack_tag in layouts/pdf.html.erb which leads to a different error.

Is there any way that I can access that function in html.erb?

CodePudding user response:

Give your paragraph a class like so:

<p ></p>

then put this

<script>
  document.getElementsByClassName('p_class')[0].textContent = sayHello();
</script>

at the bottom of your app/views/invoices/pdf.html.erb partial.

  • Related