I thought it would be nice if there was a share share button in the page with Rails, so I searched variously on the net. Many of them depended on Gem, so I decided to leave an article for myself.
Rails: 6.0.2.1
First, let's prepare an icon for the share button. This time I will use Font Awesome.
Font Awesome is installed from yarn.
yarn add @fortawesome/fontawesome-free
If you have not installed Webpacker in your project yet, please install it after the following command.
rails webpacker:install
After the installation is completed, import the installed Font Awesome into the file under ʻapp / javascript /`.
application.js
require("@fortawesome/fontawesome-free/js/all")
import '../stylesheets/application';
It will also be read on the scss side.
mkdir app/javascript/stylesheets
touch app/javascript/stylesheets/application.scss
application.scss
$fa-font-path: "~font-awesome/fonts/";
@import '@fortawesome/fontawesome-free/scss/fontawesome';
Let's also change the style_sheet_link_tag and javascript_pack_tag parts of views / application.html.erb
as follows.
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
Finally, add css for the icon color of application.scss and you're ready to go.
/* Twitter icon */
.twitter{color: #1da1f2}
/* Facebook icon */
.facebook{color: #4267b2}
This time, I set the share button on the views side as shown below.
<%= link_to "https://twitter.com/intent/tweet?url=http://localhost:3000/" do %>
<i class="fab fa-twitter-square fa-4x twitter"></i>
<% end %>
<%= link_to "https://www.facebook.com/share.php?u=http://localhost:3000/" do %>
<i class="fab fa-facebook-square fa-4x facebook"></i>
<% end %>
The share button on Twitter allows you to share using Tweet Web Intent. This time, only the url is set, but it seems that the following settings can also be made.
option | Contents |
---|---|
text | Body settings |
hashtag | Hashtag settings |
url | URL settings |
&
For the share button on Facebook side, you can implement the share button by writing the URL you want to share at the end of https://www.facebook.com/share.php?u=
.
Both URLs set this time are localhost URLs. When actually implementing it, be careful not to forget to change it to the link you want to share.
Recommended Posts