Getting HTML from a Template2:19 with Jay McGavren
Ruby strings work okay for responding with short HTML snippets. But they're not going to work so well for full pages. That's why Sinatra has a feature that makes it easy to load text in from files: ERB templates. We can use an ERB template to generate our response to the browser.
Ruby strings work okay for testing short HTML snippets. 0:00 But it's not going to work so well for full pages. 0:04 That's why Sinatra has a feature that makes it easy to load in text from files 0:07 ERB templates. 0:11 ERB stands for Embedded Ruby. 0:13 It allows you to take a text file such as HTML template that always shows the same 0:15 static text and embed Ruby code into it that displays changing dynamic data. 0:20 We'll talk about embedding data into ERB in a bit. 0:26 For right now we're just going to place some static unchanging HTML into an ERB 0:29 template file and load that in as the HTML we're going to display. 0:34 Sinatra loads ERB templates in from of 0:38 view sub directory within your apps main directory. 0:41 So let's create that directory now. 0:43 I'll choose a new folder and name it views. 0:46 Within that folder, I need to create a file whose name ends in a .erb extension, 0:54 so I'll choose a new file and 0:59 name it welcome.erb Then I'll go back into my main app. 1:03 Remove the HTML string from our route and move it into the welcome.erb file. 1:10 Making sure to remove the quote marks from the string. 1:16 I'll save that and then in the route I will call a Sinatra method called erb. 1:19 The erb method loads a template file from the views directory, renders it and 1:25 returns the result as a string. 1:29 Since our template doesn't have any erb tags and 1:31 the result will be the same HTML string as before. 1:34 You pass an argument to the erb method with the name of the file you want 1:37 to render as a symbol and leave in the .erb extension off. 1:41 So we use a symbol of :welcome and that'll render the welcome.erb file. 1:45 Since our template doesn't have any erb tags in it, 1:51 the result will be the same HTML string as before. 1:53 Let's try it out and see if it still works the same. 1:57 I'll go to my console, stop my server if it's running and then run it again. 2:00 Then in the preview, I'll click refresh. 2:06 We get the same HTML as before. 2:10 Welcome to our Wiki is a level one heading. 2:12 But now that our HTML is in a file, 2:14 it'll be easier to add more code to the template. 2:16
You need to sign up for Treehouse in order to download course files.Sign up