Passing Data to Templates

We’ve skirted around one of the more complex areas of ERB: how to access variables from within our templates. We’ve seen that, by default, our templates are evaluated as though they were top-level Ruby code, allowing them access to variables in that scope. But in practice, that’s unworkable. We don’t want to create variables in the top-level scope if we can help it.

We need to be able to control the scope that our templates are evaluated in. We do this by passing a binding to ERB when our template is compiled. This binding holds information about the variables currently in scope. (These bindings aren’t a feature of ERB; they’re a concept within Ruby itself.)

It’s much easier to illustrate this with an example. So, ...

Get Text Processing with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.