href
我正在编写一个宏,它接受一个字符串并根据该字符串返回一个。该字符串可能有 150 个不同的值。我的问题是如何以高效的方式编写它。使用pdflatex
。
以下是我现在得到的,简化为两个条件以供解释:
\documentclass{article}
\usepackage{hyperref}
\newcommand{\myref}[1]{%
\ifnum\pdfstrcmp{#1}{aaa}=0%
\href{example.com/aaa}{my aaa link}
\fi
\ifnum\pdfstrcmp{#1}{bbb}=0%
\href{example.com/bbb}{my bbb link}
\fi
}
\begin{document}
Here is \myref{aaa}.
\end{document}
但当然,一旦我成功了(#1=aaa
比如说),我仍然会毫无理由地测试其他 149 个条件。如何有效地编写代码?
答案1
例如,我将创建命令名称:
\documentclass{article}
\usepackage{hyperref}
\makeatletter
\@namedef{aaa@link}{\href{example.com/aaa}{my aaa link}}
\@namedef{bbb@link}{\href{example.com/bbb}{my bbb link}}
\newcommand{\myref}[1]{%
\csname #1@link\endcsname}
\begin{document}
Here is \myref{aaa}.
\end{document}
答案2
让 biber 为您搜索:
假设有一个test.bib
文件
@online{tex,
note={my aaa text},
url={tex.stackexchange.com}
}
@online{google,
note={my bbb text},
url={www.google.com}
}
然后
\documentclass{article}
\usepackage{biblatex}
\addbibresource{test.bib}
\DeclareFieldFormat{url}{\href{#1}{\printfield{note}}}
\DeclareCiteCommand{\myref}{}{\usebibmacro{url}}{}{}
\usepackage{hyperref}
\begin{document}
Here is \myref{tex}
\myref{google}
\end{document}
答案3
您可以使用xparse
:
\pdfcompresslevel=0
\documentclass{article}
\usepackage{xparse}
\usepackage{hyperref}
\ExplSyntaxOn
\NewDocumentCommand{\newref}{mmm}
{% #1 = key, #2 = URL, #3 = description, #4 = options for \href
\prop_gput:Nnx \g_tima_sites_prop { #1 @ url } { \tl_to_str:n { #2 } }
\prop_gput:Nnn \g_tima_sites_prop { #1 @ desc } { #3 }
}
\NewDocumentCommand{\myref}{m}
{% #1 = key
\tima_href:xx
{ \prop_item:Nn \g_tima_sites_prop {#1 @ url } }
{ \prop_item:Nn \g_tima_sites_prop {#1 @ desc } }
}
\prop_new:N \g_tima_sites_prop
\cs_new_protected:Nn \tima_href:nn { \href{#1}{#2} }
\cs_generate_variant:Nn \tima_href:nn { xx }
\ExplSyntaxOff
\newref{texworks}{http://profs.scienze.univr.it/~gregorio/introtexworks}{\TeX works intro}
\newref{arara}{http://profs.scienze.univr.it/~gregorio/introarara}{Arara intro}
\newref{tex.sx}{https://tex.stackexchange.com}{Nice site}
\begin{document}
\myref{texworks}
\myref{arara}
\myref{tex.sx}
\end{document}