关闭

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

353人阅读 评论(0) 收藏 举报

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.

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23206次
    • 积分:444
    • 等级:
    • 排名:千里之外
    • 原创:21篇
    • 转载:10篇
    • 译文:0篇
    • 评论:0条
    文章分类