Linking Ruby with HTML Code

无人久伴 提交于 2020-03-25 11:34:27

问题


I am aware that you can implement Javascript code to an HTML documents, by inserting the code between the <script></script> tags.. is there a similar way to do this with Ruby?


回答1:


Client Side Ruby (Ruby on the browser?!)

If your question refers to executing Ruby code on the browser, like you would execute Javascript (the server isn't involved), than it's not really possible in the traditional sense.

However, Opal will "compile" your Ruby code into Javascript, allowing you to execute the compiled "Ruby" (now javascript) code within the browser, just like native Javascript (sometimes even better, as Opal attempts to optimize your code).

Server Side Ruby

Ruby is often used to run code on the server rather than the browser. There are a number of solutions.

For example, you can use ERB templates - here's a good intro to ERB - as well as other Ruby template engines (i.e. the amazing Slim template engine) to run Ruby code in a similar way to PHP code (only easier to write and maintain).

However, Ruby is much more powerful than simple templates. There are whole servers and frameworks written in and for Ruby, allowing you very powerful server-side scripting.

The common frameworks:

  • Ruby on Rails is a very common framework many beginners often start with.

  • Sinarta is also a good starting point, usually favored by more experienced coders who tend to believe it's less heavy than Rails.

  • Using Rack directly (with no framework) is the hi-performance mainstream choice, but it requires more knowledge.

  • Read the following link for more common Http-Web frameworks and Benchmarks.

There are also more experimental, or less common, frameworks - usually ones focusing on real-time web applications, such as Volt and Plezi.




回答2:


This might be a good page get the beginning ideas of how to implement RoR. Here's a snippet from the page. As you can see you can do RoR right inline in HTML with the <% and %> beginning and ending tags.

<%= form_for :article do |f| %>
  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>



回答3:


Yep, there's a templating system known as embedded ruby (erb). In here, you can place ruby code inside html tags. Ruby code is embedded with a pair of <% and %> delimiters. However, to output the value to the view, the first pair needs to be <%=

Here's a simple example.

<ul>
  <% 3.times do %>

    <li>list item</li>

  <% end %>
</ul>

Your files are typically named like index.html.erb

Here's much more information on the subject

https://en.wikipedia.org/wiki/ERuby



来源:https://stackoverflow.com/questions/34056486/linking-ruby-with-html-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!