Raw Mako template included in another in Pylons - pylons

I'm trying to include a raw Mako template to make it appear in a textarea with Pylons.
In Pylons, I know I can include one Mako template in another like this:
<html>
<body>
Here is some HTML. Now, I want to include a template.
<%include file="${c.a_mako_template}" />
</body>
</html>
Is there a way that I can do the same thing, but have the template appear as raw markup rather than passing through Mako renderer? I'm imagining something like:
<%include file="${c.a_mako_template}" render="false" />
If that sort of thing is impossible, is the best route to write a Pylons controller that does the inclusion at a later stage?
Could I somehow wrap the file to be included in <%text> tags on the fly, perhaps using <% def>?

I've figured out a sort of workable solution. It still has one rough bit, but it works.
<%
path = '/path/to/file/'
f = open(path + c.sourcefile, 'r')
text_to_edit = f.read()
f.close()
%>
<textarea id="code">
${text_to_edit}
</textarea>
The first part is just a chunk of Python embedded in the template. It opens the file and extracts the text, thereby bypassing Mako.
The rough bit is the hardcoded path. I'll have to pass that as c.path, or something like that.

Related

Displaying user input html with newlines

I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is
Hello, this is the code: <a href='foo'>foo</a>
Bye
I want it to be displayed just as above. The same with anything else, including iframe tags.
The closest I got is:
= simple_format(comment.body)
but it sanitizes html code and it's not displayed. Example: foo <iframe>biz</iframe> bar is displayed as:
foo biz bar
What should I do to achieve what I want?
Just use it without any method, it will be rendered as plain text:
= comment.body
Using your second example, the output will be:
foo <iframe>biz</iframe> bar
To make \n behave as <br>, you can use CSS:
.add-line {
white-space: pre-wrap;
}
And use it in your view:
.add-line = comment.body
Using your first example:
comment.body = "Hello, this is the code: <a href='foo'>foo</a>\n\nBye"
The output will be:
Hello, this is the code: <a href='foo'>foo</a>
Bye
Having done something similar in the past, I think you must first understand why HTML is sanitized from user input.
Imagine I wrote the following into a field that accepted HTML and displays this to the front page.
<script>alert('Hello')</script>
The code would execute for anyone visiting the front-page and annoyingly trigger a JS alert for every visitor.
Maybe not much of an issue yet, but imagine I wrote some AJAX request that sent user session IDs to my own server. Now this is an issue... because people's sessions are being hijacked.
Furthermore, there is a full JavaScript based exploitation framework called BeEF that relies on this type of website exploit called Cross-site Scripting (XSS).
BeEF does extremely scary stuff and is worth taking a look at when considering user generated HTML.
http://guides.rubyonrails.org/security.html#cross-site-scripting-xss
So what to do? Well if you checked in your DB you'd see that the tags are actually being stored, but like you pointed out aren't displayed.
You could .html_safe the content, but again I strongly advise against this.
Maybe instead you should write an alternative .html_safe method yourself, something like html_safe_whitelisted_tags.
As for removing newlines, you say you want to display as is. So replacing /n with <br>, as pointed out by Michael, would be the solution for you.
comment.body.gsub('\n', '<br />').html_safe_whitelisted_tags
HTML safe allows the html in the comment to be used as html, but would skip the newlines, so doing a quick replace of \n with <br /> would cover the new lines
comment.body.gsub("\n", "<br />").html_safe
If you want the html to be displayed instead of rendered then checkout CGI::escapeHTML(), then do the gsub so that the <br /> does not get escaped.
CGI::escapeHTML(comment.body).gsub("\n", "<br />")

Variable dustjs partial name

I am setting up some heavy split testing using dust.js on my single page app.
The base template looks like (simplified):
{>"layouts/master" /}
{<body}
<div id="container">
{?home}{>homeWelcome/}{/home}
</div>
{/body}
What I'm trying to do is have a folder containing N versions of the homeWelcome partial, and send N through the model to select the right template, like so :
{<body}
<div id="container">
{?home}{>/splits/homeWelcome_{partialNumber}/}{/home}
</div>
{/body}
But it (unsurprisingly) doesn't compile.
I could send params to the one homeWelcome template, and have all my splits in there but some are radically different from the others and it'd make for one hell of a long file.
In addition to that, I want to be able to add/remove partials in the splits directory dynamically (partialNumber is a rand from 1 to the number of files in the dir).
Any ideas how to achieve that?
Just add double quotes around the partial name and dust will happily parse the string before including a partial.
Note that partial names don't necessarily relate to folder structure, but I'm assuming you are compiling your templates with the appropriate names.

Rails erb vs gsub dynamic template performance

In my project, I am using the ERB as template engine. We have one page which used ERB template and it's loaded within 5-7 seconds.
The same page we changed it into dynamic template, the template values are stored in the database.
sample template
<p> {{name}} </p>
<p> {{address}} </p>
<p> {{mobile number}} </p>
For applying the actual values over dynamic template, i have used the gsub. This case the same page takes load time as 16-20 seconds. I used 17 gsub over dynamic template.
How erb rendering is fast? (Because i am using the same content
before and after dynamic template)
Is there any way to increase the performance?
Note:
Compared to 'gsub' method, 'sub' method is fast. But in my case i need to use global sub (gsub).
In my case, the whole page is like a dynamic template with 20 tags. In that case gsub is not a correct solution to replace the 20 tags.
Client Side:
I have used the client side template engine called Handlebar.js. Using this my page loads with normal speed.
Server Side:
https://github.com/Shopify/liquid
If you store templates in database then you could use appropriate tools to render them. If it's erb then just use ERB, don't gsub variables manually. The reason why erb is so much faster than manual gsub is because erb template gets compiled to ruby code (like "Foo <%= bar %>" becomes "Foo " + bar) and executed.
As I understand you want to store your templates in database and render them both on server and client. You can use mustache for that, it's framework-agnostic and safe to run on server.

Searching for contents between two specified tags

I installed Nokogiri into a Rails project and it can currently run "Nokogiri HTML Parser Example" with no issues.
I'm trying to create a Rails project that will parse a movie script from IMDB, conduct a word count, then display the most occurring words from that section. I've identified that the scripts are kept in a "table":
<table width=100% border=0 cellpadding=5 class=scrtext><tr><td class=scrtext><pre><html><head></head><body>
<b>PERSON1</b>
They say some dialogue
<b>PERSON2</b>
They say some more
</pre></table>
I would like to exclude the text within the <b>/<b> brackets as well.
I've been setting this up like the example above in the controller, and have gotten as far as taking in the URL:
#Save as a temp. file
tmp_file = open('http://www.imsdb.com/scripts/Authors-Anonymous.html')
#Parse the temp. file
doc = Nokogiri::HTML(tmp_file)
I'm having difficulty understanding how to set the CSS constraints to grab this table. I understand that it's between those <pre>/<pre> tags, and I've followed a number of tutorials for this but I still don't understand how to set up those constraints.
I feel that the code following this should be something like this, but I'm not awfully sure:
doc.search("//pre")
How do I set up Nokogiri's CSS constraints to pull the content between two tags such as <pre></pre>, and then filter out irrelevant tags such as <b></b> that will occur within the output?
You can use the css method selector: doc.css('pre b') which will get every <b> tag(s) inside every <pre> tag(s):
doc.css('pre b').each do |b_tag|
# b_tag will be a String containg like `<b>this text is bold</b>`
end
It might not be the most elegant solution but it did the trick for me.
In the controller, I defined the following:`
def index
page = [THE_URL]
doc = Nokogiri::HTML(open(page))
#content = doc.css('b').remove
#content = doc.css('pre')
puts #content
end
and then in the View;
<%=#content %>

Correct coding convention for embedded code on web page templates

I had come experience with PHP a time ago and now I'm learning to use Ruby on Rails. But one simple question bothered me in both these languages, so I think I can cross-post it to both tags.
As you know, one of the concepts there is that one can embed PHP or Ruby code into web page template. Then these statements are executed and result of its execution is inserted in certain places of the page, marked with "brackets" <%= ... %>.
Or... wait. We program Ruby/PHP, but not HTML. Maybe we should treat template as Ruby/PHP code, into which sometimes HTML markup is inserted? So the process is treated like that HTML are inserted into ruby code into the "brackets" %> ... <%.
These are two different approaches:
HTML page is the primary entity, and it is affected by code execution; or
code is the primary entity, and it is executed, while HTML snippets are inserted in certain places.
This philosophy leads to different possibilities in coding conventions: result of code execution influences the page If we adhere the first insight, then the code would look like this:
<p>
<% (1..10).foreach do |i| %>
Iteration number <strong><%= i %></strong>. <br/>
<% end %>
</p>
But if we stick to the second alternative, the code would be formatted like this:
<%
%><p><%
(1..10).foreach do |i|
%>Iteration number <strong><%
%><%= i %><%
%></strong>. <br/><%
end
%>
How should the concept of templates be construed? What concepts do you, way more experienced Web developers, account for the coding convention?
If this is in your View layer (and it should be), then the HTML is the primary entity. It's the most pertinent part of that layer -- marking up your data to display in meaningful ways to the user.
Even aside from that, your second example is nearly unreadable. I see what you're doing, but it took me a minute to wrap my brain around it. I've also never, ever seen View-layer code like your second example (and I would make it one of my priorities to change it wherever I saw it if it was in a project I was working on).
To be more concise: you're putting the emphasis on the wrong thing. In my opinion, readability trumps just about everything else. The coding style that produces the most readable code is therefore the most superior (ceteris paribus and YMMV, of course).
Maybe you should look into Haml? I don't know if there's a php equivalent, but as far as Rails goes, it's somewhere in between the two schemes. It's not quite code centric. But when used right, all the raw html is prepared programatically.
In short everything is considered text to be directly outputted, unless prefixed with either a %, - or =. Which translate to html-tag, ruby code that doesn't output. Ruby code that does output. Haml then uses whitespacing to nest things properly, much like python does. Raw html outputs untouched but using % to specify a tag handles closing tags.
Sample:
#outer-div
- #items.each do |i|
%span.item
= i
%br
Outputs
<div id="outer-div">
<span class="item">
item
</span>
<br>
</div>
See the haml tutorial for more information.
To answer the central question. The bulk of any page is going to be HTML or raw text. We reduce the bulk of that text with includes and helpers, but it's still there. If there were a truly code centered approach my use of it would depend on the ratio of program logic to html. Personally I'd rather go with the html centered approach.
If you are interested in a code-oriented view, this is something you might try implementing as a pure Ruby DSL:
tag :p, :class => 'iterations-container' do
(1..10).each do |i|
text "Iteration number "
tag :strong { text i }
text "."
tag :br
end
end
Or perhaps instead of tag :p do ... end, you may favor tag.p do ... end.
I recommend doing only very simple logic in your template files. That way designers who can edit HTML can easily edit even those files to alter the layout if need be.

Resources