Jun 21. 2018 · by Helge Sverre

Adding an "edit this page" link in Craft CMS

I find it helpful to myself and content editors to always add an "edit this page/article" link on the frontend of a craft site, so that they can quickly get in there and change something if they need to.

templates/layout.twig
TWIG
<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>

<nav>
    <ul>
        <li><a href="/"></a></li>
        <li><a href="/about"></a></li>
        <li><a href="/blog"></a></li>
        
        <!-- This is the important part -->
        {% if currentUser and entry is defined %}
            <li>
                <a href="{{ entry.cpEditUrl }}">Edit this entry</a>
            </li>
        {% endif %}
    </ul>
</nav>

{% block content %}{% endblock %}

</body>
</html>

The currentUser variable is a global variable that refers to an UserModel, the variable is only available if a user is signed in.

The entry variable refers to the current entry (A channel entry, a single or a structure entry), the entry variable is not defined if you are in a template that is not tied to an entry (if you didn't point to the template in your section config, it probably does not have an entry)

Alternatively
If you just want a "drop in" solution to this problem, check out the plugin called Admin Bar, it will add a WordPress-like admin bar to the top of the page for logged in users with a link to edit the current entry.