How to insert my HTML/template inside each <body> tag? - ruby

I would like to insert a piece of arbitrary HTML code (or preferably another Markaby template) inside the <body> tag in each of my webapp pages.
I'm using Markaby which means that a template is (more or less) a Ruby class and body is its method. So it must be possible to write some Ruby code to intercept the body method call and to insert my HTML.
How do I do that with Sinatra?

What's preventing you from using <%= yield %> in your layout? For example, the code below will render your current view inside the layout's <body> tags by using <%= yield %>
In this case the template is layout.erb and the page is hello.erb. hello.erb is rendered within layout.erb in place of the <%= yield %>statement. Is this what you meant?
require 'sinatra'
get '/hello/:name' do
#name = params[:name]
erb :hello
end
__END__
## layout
<html>
<body>
<%= yield %>
</body>
</html>
## hello
<h3>Hello <%= #name %>!</h3>
Code from About.com - Sinatra

That can be done by redefining the body method in Markaby Builder class. This piece of code will do it:
class Markaby::Builder
alias body_orig body
def body(*args, &block)
str = capture(&block)
block = proc { text('ON EVERY PAGE' + str) }
body_orig(*args, &block)
end
end
And this one will include another Markaby template as the first thing inside the body tag:
class Markaby::Builder
alias body_orig body
def body(*args, &block)
str = capture(&block)
str2 = render :mab, :include_template_name, *args
block = proc { text(str2 + str) }
body_orig(*args, &block)
end
end

Related

How to render a value from an .rb file into an .erb file

I don't have much experience with Ruby all I wan't to do is render a value that I declare in an .rb file in an .erb file.
In my .rb file I have this:
def abc()
begin
"aaaaa"
end
end
In my .erb file I have this:
Hello <% abc %>
When I run the app I only see:
Hello
But I expect to see:
Hello aaaa
Anybody can give me a hand, I don't really know ruby at all. Also I have no idea if this is ruby or ruby on rails so sorry if the tag below is wrong.
In Sinatra, register your method as a helper in .rb file:
helpers do
def abc
"aaaaa"
end
end
Omit parentheses if your methods don't need arguments. Also, begin/end block isn't necessary here.
You can call your helper in .erb template:
<%= abc %>
Don't forget = in the opening tag.
http://sinatrarb.com/intro.html section 'Helpers'.
It's unclear what you want to achieve. But If you just want some text in your erb you can do something like this:
erb :myerb, locals: {text: "aaaaa", saved: false}
myerb.erb
<% if saved %>
Hello <%= text %>
<% endif %>
This would also work for functions.
First of all, you need to be aware that a defined method inherently includes the functionality of a begin/end block so you don´t need to put them again. Assuming you are using sinatra, here is what I think you need:
my.rb
require 'sinatra'
def abc
"aaaa"
end
get '/' do
erb :my, locals: {variable: abc}
end
my.erb
<html>
<body>
<p>
Hello <%= variable %>
</p>
</body>
</html>
Run ruby my.rb and then open http://localhost:4567/

How do I define a method in Ruby to have the same function of escapeHTML?

I want code that uses a method named "h" to have the same output this code in ERB does:
<code>
<%= CGI::escapeHTML(the_string) %>
</code>
Output of above code:
<!doctype html> <head><meta charset="utf-8"><title>Black Cat</title></head> <img
src=blackcat.gif /> <script type="text/javascript">alert('If you see this, your\'re
vulernable to XSS!');</script>
Output of above code in website form for clarification: http://hills.ccsf.edu/~wly3/cs132a/lab4.cgi
Two questions:
1) How should I modify this code to incorporate escapeHTML and to remove unnecessary code? (I'm not sure which requires/includes I need)
module CgiHelper
require 'cgi'
require "erb"
include ERB::Util
def h
#code
end
2) How should I modify the ERB in the beginning so that it works with the "h" method?
Any help is appreciated. Trial and error hasn't returned results for a while.
1) Create the h helper method
module CgiHelper
require "erb"
include ERB::Util
def h(s)
html_escape(s)
end
end
2) Use the h helper method
<code>
<%= h(the_string) %>
</code>

How to implement form_tag helpers without actionview?

I'm working on a Sinatra app and want to write my own form helpers. In my erb file I want to use the rails 2.3 style syntax and pass a block to a form_helper method:
<% form_helper 'action' do |f| %>
<%= f.label 'name' %>
<%= f.field 'name' %>
<%= f.button 'name' %>
<% end %>
Then in my simplified form helper I can create a FormBuilder class and yield the methods to the erb block like so:
module ViewHelpers
class FormBuilder
def label(name)
name
end
def field(name)
name
end
def button(name)
name
end
end
def form_helper(action)
form = FormBuilder.new
yield(form)
end
end
What I don't understand is how to output the surrounding <form></form> tags. Is there a way to append text on only the first and last <%= f.___ %> tags?
Rails has had to use some tricks in order to get block helpers to work as wanted, and they changed moving from Rails 2 to Rails 3 (see the blogposts Simplifying Rails Block Helpers and Block Helpers in Rails 3 for more info).
The form_for helper in Rails 2.3 works by directly writing to the output buffer from the method, using the Rails concat method. In order to do something similar in Sinatra, you’ll need to find a way of writing to the output from your helper in the same way.
Erb works by creating Ruby code that builds up the output in a variable. It also allows you to set the name of this variable, by default it is _erbout (or _buf in Erubis). If you change this to be an instance variable rather than a local variable (i.e. provide a variable name that starts with #) you can access it from helpers. (Rails uses the name #output_buffer).
Sinatra uses Tilt for rendering templates, and Tilt provides an :outvar option for setting the variable name in Erb or Erubis templates.
Here’s an example of how this would work:
# set the name of the output variable
set :erb, :outvar => '#output_buffer'
helpers do
def form_helper
# use the new name to write directly to the output buffer
#output_buffer << "<form>\n"
# yield to the block (this is a simplified example, you'll want
# to yield your FormBuilder object here)
yield
# after the block has returned, write any closing text
#output_buffer << "</form>\n"
end
end
With this (fairly simple) example, an Erb template like this:
<% form_helper do %>
... call other methods here
<% end %>
results in the generated HTML:
<form>
... call other methods here
</form>

What would the erb template look like for a ruby enumerator?

What would the erb template look like for a ruby enumerator? The answer will be a erb template.
require "erb"
# build data class
class Foo < Array
def build
b = binding
# create and run templates, filling member data variables
ERB.new(File.read('test2.erb')).result b
end
end
# setup template data
bar = Foo.new([1,2,3])
puts bar.build
I would like some way of accessing the 1,2,3 items in the erb template.
Focus on Ruby 1.9.3 compatibility.
Note: the Class is an extension of Array, and I want to access the elements of this array in its erb template.
Ok, it was as simple as reaching into the self reference.
<% self.each{|element| %> <%= element %> <% } %>

How to correct in the Sinatra show block

Sorry, I will not use the specific expression in English.
index.erb
<h1>Hello World.</h1>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
<% capture_content :key do %>
I'm Here.
<% end %>
helpers
def capture_content(key, &block)
#content_hash = {}
#content_hash[key] = block.call # this block contains erb all
end
I just want capture_content in content
I hope expression is correct T_T
If you are looking to write yourself the Sinatra equivalent of the Reails content_for helper then you don't need to.
Because there is an extension called Sinatra::ContentFor which is part of the Sinatra::Contrib project which does what you want.
From the documentation:
Sinatra::ContentFor is a set of helpers that allows you to capture
blocks inside views to be rendered later during the request. The most
common use is to populate different parts of your layout from your
view.

Resources