• [sinatra] Just Do It: Learn Sinatra, Part One Darren Jones


    1. Install sinatra gem

    gem install sinatra --no-ri --no-rdoc
    

    2. Basic App

    #!/usr/bin/ruby
    require 'sinatra'
    get '/' do
    	"Just Do It"
    end
    

    ruby低于1.9,需要在文件开头加require 'rubygems'

    ruby basic.rb
    

    Open up your browser and go to http://localhost:4567.

    3. Inline Template

    Slim is a fantastic template engine that makes this a much easier task.

    Install slime: $ gem install slime

    #!/usr/bin/ruby
    require "sinatra"
    require 'slim'
    
    get '/' do
    	slim:index
    end
    
    #Inline templates always come after the __END__ declaration, and each template begins with @@.
    
    __END__
    
    @@layout
    doctype html
    html
    	head
    		meta charset="utf-8"
    		title Just Do it
    		link rel="stylesheet" media="screen,projection" href="/style.css"
    		/[if lt IE 9]
    			script scr="http://html5shiv.googlecode.com/svn/trunk/html5.js"
    	body
    		h1 Just Doi it
    		== yield 
    
    
    @@index 
    h2 My tasks
    ul.tasks
    	li Get Milk		
    

    "@@layout" template: This will automatically be rendered with every view and provides a basic HTML5 scaffolding. The key line in the layout template is right at the end (==yield). The yield statement renders the content from the whichever template was requested by the handler (in this case, ‘index’).

    4. Extend Views (把视图分离出来)

    5. Dynamic Content

     在主文件rb中增加代码

    get "/:task" do
    	@task=params[:task].split('-').join(' ').capitalize
    	slim :task
    end
    

    ‘@task’ equal to the value of params[:task]

    对应的视图文件task.slim

    h2 My Tasks
    = @task
    

    其中@task匹配对应的URL。

    6.Forms(窗体处理)

     本例把index.slim的内容替换成

    form action="/" method="POST"
      input type="text" name="task"
      input.button type="submit" value="New Task >>"
    

    这样会在“/”页面显示一个窗体(一个文本框、一个提交按钮)

    提交的内容需要一个handler来处理,再sinatra文件中用post(对应窗体提交method),代码如下:

    post '/' do
      @task =  params[:task]
      slim :task
    end
    
  • 相关阅读:
    D. Almost All Divisors
    G
    K
    L3-016 二叉搜索树的结构 (30 分)
    D. Colored Boots(STL)
    O
    [论文]Clustering-Based Ensembles as an Alternative to Stacking
    [LeetCode] Factorial Trailing Zeroes 阶乘末尾0
    [LeetCode] Maximum Depth of Binary Tree dfs,深度搜索
    [LeetCode] Count and Say 字符串
  • 原文地址:https://www.cnblogs.com/lizunicon/p/3600814.html
Copyright © 2020-2023  润新知