《Agile Web Development with Rails》读书笔记(三)

Make Dynamic Pages

In order to get dynamic pages, I need to embed some ruby code into the *.rhtml in views.

First, I introduce some symbols in *.rhtml.

<%= %> : content between <%= %> is interpreted as ruby code and executed. The result of that execution is converted into a string, and that value is substituted into the file in place of the <%= %> sequence.

<% %> : mostly the same as <%= %>, except the result did not display—never converted into a string and never substituted into the file.

<%= -%> : tell rails to remove any new line that follows from the output.

h( ) : prevent the special characters from grabling the browser display—they’ll escape as html entities.

Now, we create a page to display the current time when you refresh the page.

In order to accord with the spirit of MVC, first we save the current time in a variable in the controller’s method, then we use the variable to display the current time in views.

work/demo/app/controllers/say_controller.rb

class SayController > ApplicationController

   def hello

      @time = Time.now

   end

end

work/demo/app/views/say/hello.rhtml

<html>

   <head>

      <title>Hello, Rails!</title>

   </head>

   <body>

      <h1>Hello from Rails!</h1>

      <p>

      It is now <%= @time %>

      </p>

   </body>

</html>

Save this file, you’ll see the current time when you refresh the page.

Our story illustrates convention over configuration, one of the fundamental parts of the philosophy of Rails.

 

Link Pages Together

There are two way to link pages together.

<a href =  “/say/goodbye”>Goodbye</a>

Rails use a convention to parse the URL into a target controller and an action within that controller. Here say is controller, goodbye is the action in say.

Flaw: the hyperlink path is relative, if we move the application to a different place on the web server, the URL would no longer be valid.

 

:action : Ruby symbol, you can think of the colon as meaning the thing named…, so :action means the thing named action, the => “goodbye” associate the string goodbye with the name action.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值