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
\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

| improve this answer | |
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

| improve this answer | |
2

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}
| improve this answer | |
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

| 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.