4

I want to be able to pass an array as a macro argument as for example :

\newcommand{\printLinks}[1]{
    //For each links in #1 print it
}

\printLinks{ {link1, link2, ..., linkn} }
% Results in \url{link1}, \url{link2} ...

Is it possible in LaTeX ?

4 Answers 4

5

You can use the listofitems package.

\documentclass{article}
\usepackage{listofitems,url}
\begin{document}
\newcommand{\printLinks}[1]{%
  \readlist*\mylist{#1}%
  \foreachitem\z\in\mylist{Link \#\zcnt{} is \expandafter\url\expandafter{\z}\\}%
}

\printLinks{link1, link2, ..., linkn}
% Results in \url{link1}, \url{link2} ...
\end{document}

enter image description here

3

Just for fun: without additional packages.

\documentclass{article}
\usepackage{url}
\makeatletter
\newcommand{\printLinks}[2][\par]{%
\@for\next:=#2\do{\expandafter\url\expandafter{\next}#1}%
}
\makeatother
\begin{document}
\printLinks{link1, link2, link3,linkn} 

\printLinks[;]{link1, link2, link3,linkn} 
\end{document}

enter image description here

3

As a third alternative you can also do this:

\documentclass{article}

\usepackage{pgffor}
\usepackage{hyperref}

\newcommand\printLinks[1]{%
    \foreach[count=\i] \j in {#1} {%
        \ifnum\i>1 , \fi%
        \url{\j}%
    }
}

\setlength\parindent{0pt}

\begin{document}

\printLinks{%
https://www.aaa.com,
https://www.bbb.com,
https://www.ccc.com,
https://www.ddd.com,
https://www.eee.com,
https://www.fff.com
}

\end{document}
2

LaTeX3 novice's solution:

\documentclass{article}

\usepackage{expl3}
\usepackage{url}
\usepackage{xparse}

\ExplSyntaxOn

\clist_new:N \l_links_printlinks
\NewDocumentCommand { \printLinks } { O{\par} m }
  {
    \clist_set:Nn \l_links_printlinks { #2 }
    \clist_map_inline:Nn \l_links_printlinks { \url{ ##1 } #1 }
  }

\ExplSyntaxOff

\begin{document}

\printLinks{link1, link2, link3, link4}

\printLinks[; ]{link1, link2, link3, link4}

\end{document}

Output:

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .