Named anchor

Named anchor Getting Started
A named anchor is a link to content in the current resource.

A typical named anchor would look something like:

<a name="prohibited"></a>

The problem with using named anchors with MODX and friendly URLs enabled is that the <base href=" "> tag required to support relative URLs will confuse browsers into thinking that any anchors point to the base href page, which will typically be your home page. Luckily, nothing is impossible with MODX, and there are (at least) two ways to overcome this problem.

Accessing a named anchor by manually adding the URL

To generate a link to the current Resource when using the named anchor “prohibited”:

<a href="[[~[[*id]]]]#prohibited">Prohibited actions</a>

To generate a link to the resource with ID 12 when using the named anchor “prohibited”:

<a href="[[~12]]#prohibited">Prohibited actions</a>

Using a plugin to automatically add the URL when using anchors

Alternatively, you can use a plugin to automatically add a link to the current resource before the actual anchor.

Place the following code in a new plugin and in the System Events tab assign it to the OnWebPagePrerender event (based on this post).

if($modx->resource->get('id') !=$modx->config['site_start']) {
  $modx->resource->_output =str_replace('href="#','href="' .$modx->makeUrl($modx->resource->get('id')) .'#',$modx->resource->_output);
}

First the code checks that we are not on the home page (if we are, there is no need to add the URL to the page). When this is not the case, it will replace any occurrences of href="# with href="link-to-page.html#, ensuring that your anchors work as intended.

With this solution, you can still link to anchors on other pages using the second example above.

Rate article
MODX 3
Add a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.