I have a text file located in my project directory that contains the link of sites as well as the location of the logos. For example:
img1 = {name => "logo1", link => "http://example.com", imgpath => "img/logo1.png"}
img2 = {name => "logo2", link => "http://foobar.com", imgpath => "img/foobar.png"}
img3 = {name => "logo3", link => "http://foobar.com", imgpath => "img/foobar2.png"}
What I would like to do is loop through that text file to display each image with its link. I've searched all over and I can't seem to find a good example on how to do it. Here's the for loop I've got so far in my page:
- File.open("img/logos.txt").readlines.each do |name,link,imgpath|
.col-sm-6.col-md-4.col-lg-3
.item-work
.hover
%img{:alt => "Image", :src => "img/#{imgpath}"}/
%a.lightbox-image{:href => "#{link}", :title => "Image"}/
.overlay
.info
%a{:href => "#{name}"} #{name}
I'm sort of close, the page loads all the logos except the images aren't there and the links are associated with them. I know it's because I didn't call them correctly in my %img
link and %a
tags but I can't seem to figure it out. How would you suggest going about doing this?
#readlines
is going to give you each line of the text file as a string. Based on your comment, this would word fine:
logos.txt:
logo1,http://example.com,img/logo1.png
logo2,http://foobar.com,img/foobar.png
logo3,http://foobar.com,img/foobar2.png
Haml:
- File.open("img/logos.txt").readlines.each do |line|
- img = line.split(',').map(&:chomp)
.col-sm-6.col-md-4.col-lg-3
.item-work
.hover
%img{:alt => "Image", :src => "img/#{img[2]}"}/
%a.lightbox-image{:href => "#{img[1]}", :title => "Image"}/
.overlay
.info
%a{:href => "#{img[0]}"} #{img[0]}
The second line is creating an array of values, like so:
[1] pry(main)> line
=> "logo1,http://example.com,img/logo1.png\n"
[2] pry(main)> line.split(',').map(&:chomp)
=> ["logo1", "http://example.com", "img/logo1.png"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.