HTML Tip: Use a button as a link

Today’s challenge was to create a link that looks like a button. Typically, I would use something like this because I typically use Bootstrap as a base theme.

<a class="btn btn-default" href="" target="_blank">Learn More</a>

When using a Bootstrap-based theme, the “btn btn-default” CSS classes on a link will cause the link to look like an HTML button, even though it isn’t. However, the site that I’m working on isn’t using a Bootstrap-based theme. And in this instance, the link is immediately preceded by another button that has some fancy javascript attached it. Since these two elements appear side by side, I decided to use a button element.

So here’s what I used in my twig template to output a Drupal link field:

{% if content.field_website_link[0]["#url"] %}
  <button onclick="
    '{{ content.field_website_link[0]["#url"] }}'
,'_blank'" type="button">LEARN MORE
{% endif %}

There’s a nice, neat condition to check and make sure that the URL value exists in the link, then creates the button with a “” action onclick. In this instance, the browser is forced to open a new window. (Yes, not ideal user experience according to the official rules, but creates stickiness for the website, so I’m okay with it.) Here is the finished look.