unixforeachautomationlatextex

How to display a box for each environment defined in Latex and actually created with \begin{env} \end{env} syntax


I have defined an environment, called question, in which I write some questions. This environment is a simple wrapbox, but it allows me to display the question as I want.

I would like to add a new page and, for each question that I have created, paint a rectangle box (to have a sort of blank space to write the answers in).

How to automate such procedure? I do not want to calculate every time how many questions are there and then write a new box for each of those questions. I would like to achieve this programmatically with some code like this:

%... rest of the LaTeX document

\begin{question}
This is the question 1, isn't it?
\end{question}

\begin{question}
This is the question 2, isn't it?
\end{question}

and then have something like:

%... rest of LaTeX document
\foreach \environment{question}{
% Paint an mbox of given size
}

Is that possible? I provide a MWE (with begin center, but it should be independent from the environment, I guess)...

%% MWE with two center environments

\documentclass{article}
\usepackage[utf8]{inputenc}
\begin{document}

%Q1
\begin{center}
Q1
\end{center}

\begin{center}
Q2
\end{center}


%% HERE I would like to obtain a loop with two iterations, one \foreach question, that I can then use to manipulate the output

\end{document}



Solution

  • You could use a counter to count the number of questions:

    \documentclass{article}
    
    \usepackage{pgffor}
    \usepackage{tcolorbox}
    
    \newcounter{qu}
    \newenvironment{question}{\refstepcounter{qu}}{}
    
    \begin{document}
    
    %Q1
    \begin{question}
    Q1
    \end{question}
    
    \begin{question}
    Q2
    \end{question}
    
    \clearpage
    
    \foreach \macro in {1,...,\thequ}{
      \begin{tcolorbox}[height=4cm,title={Answer for Q\macro}]
      \end{tcolorbox}
    }
    \setcounter{qu}{0}
    
    \end{document}
    

    enter image description here