Laravel/Blade - Extend same template multiple times on same page - laravel

So there must be a simple way around this... On my site there are multiple modals, depending on the page. I've created a modal template that these can all extend. However, the last modal I include on the page ends up 'taking over' the rest of them, and so all my modals end up with the same sections from that last include. How can I make it so that each extension is unique to the file from which it extends?
Example of what's happening:
//template.blade.php
<htmls and stuff>
#yield('section_1')
#yield('section_2')
</htmls and stuff>
//Modal 1
#extends('template')
#section('section_1')
Some words
#stop
#section('section_2')
More words
#stop
//Modal 2
#extends('template')
#section('section_1')
Rabbit
#stop
#section('section_2')
Stew
#stop
Instead of two unique modals being loaded, I end up with two modals full of Rabbit Stew.

Try using the #overwrite command instead of #endsection
Example:
#section('stuff')
Stuff goes here...
#overwrite
Source: https://github.com/laravel/framework/issues/1058#issuecomment-17194530

I personally would use includes in this instance, unless you've got markup in your sections. If it's just text you could do something like this:
//template.blade.php
<htmls and stuff>
{{ $section1 }}
{{ $section2 }}
</htmls and stuff>
//Modal 1
#include('template', ['section1' => 'Some words', 'section2' => 'More words'])
//Modal 2
#include('template', ['section1' => 'Rabbit', 'section2' => 'Stew'])

I had the same problem. I really wanted to use Blade templates too, but ended up using php includes, even with basic html markup.
//Modal 1
#include('layout.template', array(
'section1' =>
'<h1>Modal 1</h1><p><b>Some</b> words</p>',
'section2' =>
'<p>Some <u>words</u></p>'
))
//Modal 2
#include('layout.template', array(
'section1' =>
'<h1>Modal 2</h1><p><b>Some</b> words</p>',
'section2' =>
'<p>Some <u>words</u></p>
'
))
The markup all works just fine, including links. Where I ran into trouble was when I wanted to use includes inside the include arrays, which I understand is not possible. That is why I wanted to use Blade Templates.

Related

Laravel Blade: What is nesting sections doing here?

I don't know what does putting a section inside another section do. In a Laravel project I'm reading, a Blade file's code is like this:
login.blade.php :
#extends('layout') #section('content')
#section('title', 'Log in')
Lots of content.
#endsection
In above, what's the point of having title section inside content section? How will it be different if title section is placed outside:
#extends('layout')
#section('title', 'Log in')
#section('content')
Lots of content.
#endsection
I tested, and both are producing same output (HTML source code).
layout.blade.php
<head><title>#yield('title')</title></head>
<body>#yield('content')</body>
Is there any case of layout.blade.php in which different outputs will be produced?
The section directive simply copies whatever you have within #section and #endsection to the name #yield place holder on the extended template.
This means it does not consider where its placed, but for clarity and readability, the second example is the right structure.
For example, this shows that the order of the directive doesn't matter
In welcome.blade.php
#extends('default')
#section('a')
This is a
#section('c', 'This is c')
#section('b')
This is b
#section('d', 'This is d')
#endsection
#endsection
In default.blade.php
#yield('c')
#yield('a')
#yield('b')
#yield('d')
The output
This is c This is a This is b This is d
The best practice is to make your code more readable by opening and closing each block:
#extends('default')
#section('a')
This is a
#endsection
#section('c', 'This is c')
#section('b')
This is b
#endsection
#section('d', 'This is d')
It's better to put them on different rows for readability sake.
First section just puts "Log in" wherever the section "title" is:
#section('title', 'Log in')
Second section has the beginning and the end and is selfdescriptive.

Dynamic basic link in mail markdown with Laravel - not a button

I can generate a basic link like so:
This is an [example link](http://example.com/).
I can generate a button with a dynamic link like so:
#component('mail::button', ['url' => \URL::to('/subscriptions/'.$recipient->id.'/'.$recipient->email.'?action=subscribe')])
Sign Me Up
#endcomponent
But how do I generate a dynamic link, not button?
I tried:
[Safe Unsubscribe]( url('/subscriptions/'.$recipient->id.'/'.$recipient->email.'?action=unsubscribe') )
and
[Safe Unsubscribe]( \URL::to('/subscriptions/'.$recipient->id.'/'.$recipient->email.'?action=unsubscribe') )
but these output in a literal way:
url('/subscriptions/'.%24recipient-%3Eid.'/'.%24recipient-%3Eemail.'?action=subscribe%27)
You are still in a blade template. So if you are not in a blade directive and you want to echo content, you have to use the curly brackets.
[Safe Unsubscribe]({{ url('/subscriptions/'.$recipient->id.'/'.$recipient->email.'?action=unsubscribe') }})

Why is XPath returning value of '0' using Ruby, Nokogiri and Watir?

I'm working on a white-hat web-crawler that will periodically log into my account and check some information for me using Ruby with Watir and Nokogiri.
Here's the simplified HTML I'm trying to pull information from:
<div class="navbar navbar-default navbar-fixed-top hidden-lg hidden-md" style="z-index: 1002">
<div class="banner-g">
<div class="container">
<div id="user-info">
<div id="acct-value">
GAIN/LOSS <span class="SPShares">-$12.85</span>
</div>
<div id="committed">
INVESTED <span class="SPPortfolio">$152.11</span>
</div>
<div id="avail">
AVAILABLE <span class="SPBalance">$26.98</span>
</div>
I'm trying to pull the $26.98. at the bottom of the excerpt.
Here are three snippets of code I'm using. They're all pretty much identical except for the XPath. The first two return their values perfectly, but the third always returns a value of "0" even though it 'should' return "$26.98" or "26.98".
val_one = page_html.xpath(".//*[#id='openone']/div/div[2]/div[1]/div/div[2]/table/tbody/tr[2]/td[1]").text.gsub(/\D/,'').to_i
val_two = page_html.xpath(".//*[#id='opentwo']/div/div[2]/div[2]/div/div[2]/table/tbody/tr[2]/td[1]").text.gsub(/\D/,'').to_i
val_three = page_html.xpath(".//*[#id='avail']/a/span").text.gsub(/\D/,'').to_i
puts val_three
I assume it's a problem with the XPath, but I've gone through dozens of XPath troubleshooting questions here and none have worked. I checked the XPath with both FirePath and "XPath Checker". I also tried having the XPath search for the "SPBalance" class but that gave the same result.
When I remove to.i from the end, it returns a blank line instead of a zero.
Elsewhere in the site when using Watir, I was able to fix problems recording a value by calling .focus, but for this piece of the code, which is more Nokogiri, using .focus causes the error message:
undefined method `focus' for []:Nokogiri::XML::NodeSet (NoMethodError)
I assume .focus doesn't work for Nokogiri.
Update: Replaced HTML with a cleaner/more complete version.
I've continued to play around with different ways of reaching that data cell, including xpath, css and a search method. Someone told me xpath wouldn't work for this page so I spent even more time trying to get css to work. Someone else told me the page had Javascript, which would prevent Watir from working. So I tried rewriting the app for Selenium instead. Selenium did not solve the problem, and created a whole host of other problems.
Update: After following advice from the Tin Man, I've found that the node is not actually visible in the HTML when it is downloaded using curl.
I'm now trying to access the node using Watir instead of Nokogiri (as he suggested).
Here's some of what I've tried so far:
avail_funds = browser.span :class => 'SPBalance'
avail_funds.exists?
avail_funds.text
avail_funds = browser.span(:css, 'span[customattribute]').text
avail_funds = browser.div(:id => "avail").a(:href => "/Profile/MyShares").span(:class => "SPBalance").text
avail_funds = browser.span(:xpath, ".//*[#id='avail']/a/span").text
avail_funds = browser.span(:css, 'span[class="SPBalance"]').text
avail_funds = browser.span.text
avail_funds = browser.div.text
browser.span(:class, "SPBalance").focus
avail_funds = browser.span(:class, "SPBalance").text
avail_funds = #browser.span(:class => 'SPBalance').inner_html
puts #browser.spans(:class => "SPBalance")
puts #browser.span(:class => "SPBalance")
texts = #browser.spans(:class => "SPBalance").map do |span|
span.text
end
So far all of the above return either blank lines or an error message.
The div class with the ID "user-info" is visible within the HTML as downloaded via curl. Everything beneath that, however, is not visible.
When I try:
avail_funds = browser.div(:id => "user-info").text
I get only blank lines.
When I try:
avail_funds = browser.div(:class => "navbar navbar-default navbar-fixed-top hidden-xs hidden-sm").text
I get actual text back! But unfortunately the string does not contain the value I want.
I also tried:
puts browser.html
Because I thought if the value where visible in that version of the HTML, as it is through my Firefox plug-in, I could parse down to the value I want. But unfortunately the value is not visible in that version of the HTML.
By first 2 commands you fetch data directly from table cell beginning from the root of the document, and in the last one you starting from the center.
Try out to give span id and get data again, and then grow up the complexity and you will find your error in xpath
The first problem is you're trying to use a long, too-long, selector that is referencing tags that don't exist:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<head>
<body class="cbp-spmenu-push">
<div id="FreshWidget" class="freshwidget-container responsive" data-html2canvas-ignore="true" style="display: none;">
<div id="freshwidget-button" class="freshwidget-button fd-btn-right" data-html2canvas-ignore="true" style="display: none; top: 235px;">
<link rel="stylesheet" href="/Content/css/NavPushComponent.css"/>
<script src="/Scripts/classie.js"/>
<script src="/Scripts/modernizr.custom.js"/>
<div class="navbar navbar-default navbar-fixed-top hidden-lg hidden-md" style="z-index: 1002">
<div class="banner-g">
<div class="container">
<div id="user-info">
<div id="acct-value">
<div id="committed">
<div id="avail">
<a href="/Profile/MyBalance">
AVAILABLE
<span class="SPBalance">$31.59</span>
EOT
doc.at('tbody') # => nil
".//*[#id='openone']/div/div[2]/div[1]/div/div[2]/table/tbody/tr[2]/td[1]"
".//*[#id='opentwo']/div/div[2]/div[2]/div/div[2]/table/tbody/tr[2]/td[1]"
There is no <tbody> tag in your sample, and there rarely is in HTML created in the wild, especially if people created it manually. We usually see <tbody> in HTML someone grabbed from a browser's "View Source" display, which is the resulting output after their engine has mangled the HTML in an attempt to make it readable. Don't use that output. Instead, ALWAYS go straight to the source and use wget or curl and download the page and inspect it with an editor, or even use nokogiri some_url on the command-line and look at it there.
A second problem is your HTML snippet is invalid because it's full of unterminated tags. Nokogiri will do fixups on bad HTML, which can actually move nodes around, making it difficult to find nodes, especially when debugging. In this particular case Nokogiri is able to terminate them, but it's important to honor tag closures.
Here's what I'd use:
value = doc.at('span.SPBalance').text # => "$31.59"
This is using CSS which is usually much more readable than XPath. at means "find the first occurrence" and is equivalent to search('span.SPBalance').first.
The XPath equivalent would be:
doc.at('//span[#class="SPBalance"]')
doc.at('//span[#class="SPBalance"]').text # => "$31.59"
Once I have the value then it's easy to manipulate it.
value[/[\d.]+/].to_f # => 31.59
Moving on...
the third always returns a value of "0" even though it should return "$31.59" or "31.59"
'$31.58'.to_i # => 0
'$'.to_i # => 0
'31.58'.to_i # => 31
'$31.58'.to_f # => 0.0
'31.58'.to_f # => 31.58
The documentation for to_f and to_i say respectively:
Returns the result of interpreting leading characters in str as a floating point number.
and
Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36).
In both cases "leading characters" is significant.
using .focus causes the error message:
undefined method `focus' for []:Nokogiri::XML::NodeSet (NoMethodError)
I assume .focus doesn't work for Nokogiri.
You could always check the NodeSet documentation, which confirms that focus is not a method.

Ruhoh - Insert Tag every x items

I'm new to Ruby and Ruhoh and have I am trying to do something like "Rails each loop insert tag every 6 items?" but I am using Ruhoh.
Basically, I have a list of posts and every 3 posts I want to create a new row div.
I have looked through all the Ruhoh documentation and there doesn't appear to be an easy way to do this. I think I need to create a plugin in Ruhoh for a collection, but having no experience in ruby I don't really understand what I am doing. Any help or guidance in the right direction would be great,
Cheers.
I'm fairly new to ruby myself, however I think this solution meets your needs!
Create a new file in the plugin directory called pages_collection_view_addons.rb (if it doesn't already exist).
Add this to that file:
module PagesCollectionViewAddons
def chunks(n = 3)
# Get all the pages
pages = all
chunks = []
# Split the 'pages' array into chunks of size n
pages.each_slice(n) { |slice|
chunks.push({pieces: slice})
}
chunks
end
end
# Inform Ruhoh of this new addon
Ruhoh::Resources::Pages::CollectionView.send(:include, PagesCollectionViewAddons)
In your template add something such as:
{{# posts.chunks}}
<div class="row">
{{# pieces }}
<h1>{{ title }}</h1>
{{/ pieces }}
</div>
{{/ posts.chunks }}
This will iterate over each of the chunks where each chunk looks like:
{pieces: [post1, post2, post3]}
Hope this helps.

Finding an Image Icon Next to a Text Item in Watir-WebDriver

The context is I'm using watir-webdriver and I need to locate if an image appears prior to a particular item in a list.
More specifically, there is a section of the site that has articles uploaded to them. Those articles appear in a list. The structure looks like this:
<div id="article-resources"
<ul class="components">
...
<li>
<div class="component">
<img src="some/path/article.png">
<div class="replies">
<label>Replies</label>
</div>
<div class="subject">
Saving the Day
</div>
</div>
</li>
...
</ul>
</div>
Each article appears as a separate li item. (The ellipses above are just meant to indicate I can have lots of liste items.)
What I want our automation to do is find out if the article has been appropriately given the image article.png. The trick is I need to make sure the actual article -- in the above case, "Saving the Day" -- has the image next to it. I can't just check for the image because there will be multiples.
So I figured I had to use xpath to solve this. Using Firefox to help look at the xpath gave me this:
id("article-resources")/x:ul/x:li[2]/x:div/x:img
That does me no good, though, because the key discriminator seems to be the li[2], but I can't count on this article always being the second in the list.
So I tried this:
article_image = '//div[#class="component"]/a[contains(.,"Saving the Day")]/../img'
#browser.image(:xpath => article_image).exist?.should be_true
The output I get is:
expected: true value
got: false (RSpec::Expectations::ExpectationNotMetError)
So it's not finding the image which likely means I'm doing something wrong since I'm certain the test is on the correct page.
My thinking was I could use the above to get any link (a) tags in the div area referenced as class "component". Check if the link has the text and then "back up" one level to see if an image is there.
I'm not even checking the exact image, which I probably should be. I'm just checking if there's an image at all.
So I guess my questions are:
What am I doing wrong with my XPath?
Is this even the best way to solve this problem?
Using Watir
There are a couple of approaches possible.
One way would be find the link, go up to the component div and then check for the image:
browser.link(:text => 'Saving the Day').parent.parent.image.present?
or
browser.div(:class => 'subject', :text => 'Saving the Day').parent.image.present?
Another approach, which is a little more robust to changes, is to find the component div that contains the link:
browser.divs(:class => 'component').find { |component|
component.div(:class => 'subject', :text => 'Saving the Day').exists?
}.image.present?
Using XPath
The above could of course be done through xpath as well.
Here is your corrected xpath:
article_image = '//div[#class="component"]//a[contains(.,"Saving the Day")]/../../img'
puts browser.image(:xpath => article_image).present?
Or alternatively:
article_image = '//a[contains(.,"Saving the Day")]/../../img'
browser.image(:xpath => article_image).present?
Again, there is also the top down approach:
article_image = '//div[#class="component"][//a[contains(.,"Saving the Day")]]/img'
browser.image(:xpath => article_image).present?
You can read more about these approaches and other options in the book Watirways.

Resources