2

How can I modify the header of a source block dynamically, based on the backend used to export my org-mode document? Specifically, I want the header to include :results output html when the file is exported to HTML, and :results output latex when the file is exported to LaTeX.

I believe that I should use the org-export-current-backend variable to achieve this, but I have been unable to write a header that does what I need.

For example, I think I could include an if call in the header. Unfortunately, this example triggers the HTML build correctly but not the LaTeX one (I can successfully export to LaTeX by inverting the if conditional):

#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) html latex)

(if (eq org-export-current-backend 'html)
  (princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
  (princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))

#+end_src

2 Answers 2

3

I think you just needed to add quotes around the values html and latex in the header elisp snippet as follows:

#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) "html" "latex")

(if (eq org-export-current-backend 'html)
  (princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
  (princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))

#+end_src

Then the code block seems to generate the right results depending on the org-export-current-backend variable.

1
  • Thanks for giving this a shot! Unfortunately, the code does not seem to be rendered properly when exported to PDF or HTML. The correct code appears in a source "block", but as raw html or LaTeX rather than a properly formatted list.
    – Vincent
    Commented Jun 19, 2021 at 19:24
2

I did not find a direct answer to my question, so I turned to an alternative that works almost as well as what I had in mind: Org-Mode Macros. In this example, we use the conditional-header macro to "decorate" the source block and dynamically change the header based on the output format. This org-mode document thus exports automatically to both PDF and HTML without altering the code.

#+MACRO: conditional-header (eval (concat "#+header: :results output " (prin1-to-string org-export-current-backend)))  

{{{conditional-header}}}
#+begin_src emacs-lisp :exports both
(if (eq org-export-current-backend 'html)
  (princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
  (princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))
#+end_src

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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