0

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?

1
  • 1
    The answer is you don't. Inline script tags are evaluated as the page is being rendered and are generally best avoided. While you can define globals from a script tag window.sayHello = function(){} you're really just asking for trouble as it will lead to timing issues. Commented Apr 27, 2022 at 17:47

1 Answer 1

1

Give your paragraph a class like so:

<p class="p_class"></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.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to call inside a <p> tag in erb file. Calling ‘sayHello()’ at the bottom will not show value inside p tag
I've updated my answer. Does this work now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.