1

The below is my MWE. I have defined a function, because I want to post many links in my document. These point to a website that shows German laws; either the overview page for that law, or, if specified (using the optional argument), jumping directly to a certain paragraph:

\documentclass[12pt]{article} 
\usepackage{hyperref}
\usepackage{ifthen}
\usepackage{xifthen}

\begin{document}

\newcommand{\gesetze}[2]{http://www.gesetze-im-internet.de/#1/
\ifthenelse{\isempty{#2}}{}{
  \textunderscore\textunderscore#2.html
  }
  }


\href{\gesetze{bgb}{622}}{This is the 622nd paragraph in the law.}
% \href{\gesetze{bgb}}{This is the main page on that law.}

\end{document}

The above works when the function \gesetze{bgb}{622} is not in the \href-argument, but just in plain text.

However, an error is shown when I want to include it in the \href-command, or when I uncomment the line where the function is handed no optional argument.

There were some weird outputs and flags in the log with the underscores, so I replaced _ with \textunderscore.

What needs to be done to make the function accept both one or two arguments, build them together as desired to create the link, and have them passed safely to hyperref?

2

You need something expandable, ifthen and xifthen won't work.

\documentclass[12pt]{article}
\usepackage{hyperref}


\begin{document}

\ExplSyntaxOn
 \newcommand{\gesetze}[2]
   {
    http\c_colon_str//www.gesetze-im-internet.de/#1/
    \tl_if_blank:nF {#2}{__#2.html}
   }
\ExplSyntaxOff
\href{\gesetze{bgb}{622}}{This is the 622nd paragraph in the law.}

\href{\gesetze{bgb}{}}{This is the main page on that law.}

\end{document}
| improve this answer | |
1

If you want to link to a specific paragraph/section or the entire law with some text more often, you can define a dedicated command for that.

I'm using etoolbox's \ifblank to test if the string is empty, because I generally prefer etoolbox tests over ifthen, but that is just a matter of style.

\documentclass[12pt]{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\newcommand{\lawlinktext}[3][]{%
  \def\lawlinktexturl{http://www.gesetze-im-internet.de/#2/}%
  \ifblank{#1}
    {}
    {\appto\lawlinktexturl{__#1.html}}%
  \href{\lawlinktexturl}{#3}}

\begin{document}
\lawlinktext[622]{bgb}{This is the 622nd paragraph in the law.}

\lawlinktext{bgb}{This is the main page on that law.}
\end{document}

Correctly linked text

An alternative definition without helper macro would be

\newcommand{\lawlinktext}[2][]{%
  \ifblank{#1}
    {\href{http://www.gesetze-im-internet.de/#2/}}
    {\href{http://www.gesetze-im-internet.de/#2/__#1.html}}}

but then we have to repeat the URL stub.

Here we also used that TeX automatically grabs the remaining argument of \href.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.