rubytemplateserubyerubis

Create your own tags/functions with Erubis


I have a ruby class that extends Erubis (a ruby templating engine) and I would like to create my own tags. The following is an example of what i'd like to be reproduce:

<%= link_to "/some/url" %>

This code should generate a html 'a' tag linking to some url. Now i'd like to be able to create my own tags such as:

<%= javascript_file "/some/javascript/file" %>

which would generate a script tag linking to some javascript file of my choice.

How can i easily extend erubis to do that?

Thanks for your time.


Solution

  • Those are just function calls that return the tag in a string:

    def javascript_file( file_path )
        "<script src=\"#{ file_path }\" type=\"text/javascript\"/>"
     end
    

    You just need to ensure that the functions are within scope at the time you call the binding.